Introduction to Algorithms 算法导论 第2章 算法入门 学习笔记及习题解答

Introduction_to_Algorithms_chap4 第四章 分治策略 阅读详情
2.1 插入排序

插入排序解决的问题:
    输入:n个数构成的序列<a1, a2, ..., an>
    输出:排序输入序列<a1, a2, ..., an>为<a1', a2', ..., an'>,满足a1' ≤ a2' ≤ ... ≤ an'

伪码:
    INSERTION-SORT(A)
      for j <- 2 to length[A]
        do key <- A[j]
            i <- j - 1
            while i > 0 and A[i] > key
                do A[i+1] <- A[i]
                    i <- i - 1
            A[i+1] = key

C代码:(C的数组下标从0开始,而伪码中从1开始)
void insertion_sort(int *arr, size_t size)
{
    int i, j, key;

    assert(NULL != arr);

    for (j = 1; j < size; ++j) {
        key = arr[j];

        for (i = j - 1; i >= 0 && arr[i] > key; --i)
            arr[i+1] = arr[i];

        arr[i+1] = key;
    }
}

正确性分析:

    说明:
        插入算法在执行循环之前,A[1,j-1]是已排好序的,而每次循环都保持这个情况,因此当j从2到length[A]循环完成后,整个数组已排序。
    初始:
        j=2,A[1,j-1]只包含一个元素A[1],因此是已排序的;
    保持:
        对于任意j(2 ≤ j ≤ length[A]),保存A[j]到key
        内部循环总是从A[j-1], A[j-2], ..., A[1]序列中依次查找所有大于A[j]的值并依次后移。
        当循环结束时,A[i+1,j]中存放所有大于key的值,而A[1,i-1]中存放所有不大于key的值,且A[i]是空闲的。
        存放key到A[i]。
        因此每次循环后,A[1,j]是有序的。
    退出:
        j > length[A]时循环结束,此时A[1,length[A]]全部有序。

数学归纳法证明:
    当j=2时,A[1,j-1]只包含一个元素A[1],因此肯定是有序的。
    假定对于任意j=m(2 ≤ m < length[A]),循环完成后有A[1,j]有序
    则当j=m+1时:
        A[1,m]肯定有序。
        保存A[m+1]到key。
        内层循环结束时,A[1,i]子数组中所有元素不大于key,而A[i+2,m+1]子数组中所有元素大于key,A[i+1]不持有有效数据。
        保存key到A[i+1]。
        综上可知:A[1,m+1]此时是有序的。

    因此对于所有的j(2 ≤ j ≤ length[A]),在任意时刻,有A[1,j]有序。
    当循环迭代到j=length[A]算法结束时,数组A已排序。

测试程序:
    可以通过如下程序测试插入排序算法的正确性。其中辅助函数print_arr、init_arr可能在以后多次用到:
#include <assert.h>
#include <stdio.h>
#include <stdlib.h>
#include <time.h>

void insertion_sort(int *arr, size_t size)
{
	int key;
	int i, j;

	assert(NULL != arr);

	for (j = 1; j < size; ++j) {
		key = arr[j];
		for (i = j - 1; i >= 0 && arr[i] > key; --i)
			arr[i+1] = arr[i];
		arr[i+1] = key;
	}
}

void print_arr(const int *arr, size_t size, const char *info)
{
	int i;

	assert(NULL != arr);

	printf("%s: ", info);
	for (i = 0; i < size; ++i)
		printf("%d ", arr[i]);
	printf("\n");
}

void init_arr(int *arr, size_t size)
{
	int i;

	assert(NULL != arr);

	srand((unsigned int)time(NULL));

	for (i = 0; i < size; ++i)
		arr[i] = rand()%100;
}

int main()
{
	int arr[10];

	init_arr(arr, 10);
	print_arr(arr, 10, "before");
	insertion_sort(arr, 10);
	print_arr(arr, 10, "after");

	return 0;
}


习题:

2.1-1 以图2-2为模型,说明INSERTION-SORT在数组A=<31,41,59,26,41,58>上的执行过程。
如下:
    31,    41(j), 59,    26,    41,    58
    31(j), 41,    59(j), 26,    41,    58
    26,    31,    41,    59(j), 41,    58
    26,    31,    41,    41,    59(j), 58
    26,    31,    41,    41,    58,    59(j)
标注为x(j)的元素表示此时正在以j执行循环。

2.1-2 重写过程INSERTION-SORT,使之按非升序(而不是按非降序)排序。
只需要更改一行:
更改
    while i > 0 and A[i] > key
为
    while i > 0 and A[i] < key
即可。

2.1-3 考虑下面的查找问题:
    输入:一列数A=<a1,a2,…,an>和一个值V。
    输出:下标i,使得V=A[i],或者当V不再A中出现时为NIL。
写出针对这个问题的线性查找的伪代码,它顺序地扫描整个序列以查找V。利用循环不变式证明算法的正确性。确保所给出的循环不变式满足三个必要的性质。
FIND-LINEAR(A, v, i)
    i <- NIL
    j <- 1
    while j ≤ length[A] and A[j] != v
        do j <- j + 1
    if j ≤ length[A]
        then i <- NIL
int find_linear(const int *arr, size_t size, int v)
{
    int i;

    for (i = 0; i < size && arr[i] != v; ++i);

    if (i == size) i = -1;    /* -1 means NIL */

    return (int)i;
}

证明:
    初始:
        i=NIL,初始化为未查找到。

    保持:
        从j=1到length[A],依次判断,如果A[j]等于v,则结束循环。

    退出:
        循环结束时,判断j是否有效
        如果j在有效范围(
Introduction to Algorithms 算法导论 第4章 递归式 学习笔记及习题解答 第4章 递归式 主方法:         n=1:                 T(n) = Θ(1)         n>1:                 T(n) = aT(n/b) + Θ(n)   (a≥1, b>1) 4.1 代换法 1). 猜测解的形式 2). 用数学归纳法找出使解真正有效的常数 改变变量: T(n) = 2T(⌊n^(1/2)⌋) 阅读详情

相关推荐

Introduction to Algorithms 算法导论 第1章 基础知识 学习笔记及习题解答

什么是算法     定义良好的计算过程,取一个或者一组值作为输入,产生一个或一组输出值。 1.1-1 给出一个真实世界的例子,其中包括着下列的某种计算问题:排序,确定多矩阵相乘的最佳顺序,或者找出凸壳。     排序:         这个是最常见的。比如:         某公司市场部季度销售额排名。         Alexa网站排名。(什么是Alexa?http:

cppgp的专栏 2087

Introduction to Algorithms 算法导论 第3章 函数的增长 学习笔记及习题解答

3.1 渐近记号 表示算法的渐近运行时间的记号是用定义域为自然数集N = {0, 1, 2, ...}的函数来定义的。这些记号用来表示最坏情况运行时间T(n)。 Θ记号     Θ(g(n)) = {f(n): 存在正常数c1,c2和n0,使对所有的n≥n0,有0 ≤ c1*g(n) ≤ f(n) ≤ c2*g(n)} O记号     O(g(n)) = {f(n): 存在正常数c和

cppgp的专栏 2829

Introduction.to.Algorithms 算法导论 答案

经典算法书籍之一, 这本答案在原书中是没有的。

算法导论(introduction to algorithms )课后习题经典解析及答案

给出了算法导论(introduction to algorithms )每一章课后习题经典解析及答案,对于初学者是一份很好的资料

Introduction to Algorithms 算法导论的习题答案及教师手册

习题答案有的并不是很详细,教师手册貌似不错,里面也有些答案,都是英文的

MIT经典教材之算法导论Introduction.to.algorithms完整版+教材+讲义+习题答案

MIT经典教材之算法导论 Introduction.to.algorithms 完整版+教材+讲义+习题答案

Introduce to Algorithms, A Creative Approach

Introduce to Algorithms, A Creative Approach .英文版

第三版课后答案Introduction to the Design and Analysis of Algorithms 3rd Edition

Introduction to the Design and Analysis of Algorithms 3rd Edition (算法分析设计基础Anany Levitin )第三版课后答案,第三版,1-12章全,有hints也有solutions,英文版

已知有两个按元素值递增有序的顺序表A和B,设计一个算法将表A和表B的全部元素归并为一个按元素值递增有序的顺序表C。

已知有两个按元素值递增有序的顺序表A和B,设计一个算法将表A和表B的全部元素归并为一个按元素值递增有序的顺序表C。

Windows 10/11系统下TurboDesign 6.4.0完整安装指南(附序列号+破解补丁)

本文提供Windows 10/11系统下TurboDesign 6.4.0的完整安装指南,涵盖系统环境预检、安装程序部署、序列号处理及破解补丁部署等关键步骤。通过详细的安装教程和优化配置,帮助用户高效完成这款涡轮机械设计软件的安装与调试,解决常见兼容性问题。

s4t5u6v的博客 1029

从ARCore到AICore:揭秘Google如何通过系统级服务推动Android生态创新

本文深入探讨了Google如何通过AICore等系统级服务推动Android生态创新。从ARCore到AICore,Google通过分层解耦策略将AI能力下沉至系统层,实现端侧大模型推理,如Gemini Nano在Pixel 8 Pro中的应用。文章剖析了AICore的技术架构、开发者赋能路径及场景化实践,展示了其在通信、内容创作和生产力工具中的卓越表现。

rust6ferris的博客 545

汽车电缆选型实战:基于ISO 19642-3~12的7类电缆电压/材料/场景对照表

本文详细解析了基于ISO 19642-3~12标准的7类汽车电缆选型实战,涵盖电压等级、导体材料和场景应用的对照表。通过全参数速查表和典型选型陷阱分析,帮助工程师快速掌握从低压信号线到高压动力电缆的选型逻辑,提升新能源汽车与智能驾驶技术的安全性和可靠性。

weixin_29043895的博客 365

【基于51】红外寻迹智能小车 - 代码篇

这是一个基于C51单片机的红外巡线智能小车,是一个适合嵌入式单片机、C语言初学者练习的小Demo,文章提供完整的项目思路、免费的源代码。

ZER00000001的博客 3万+

5个实战必备的多模态情感分析数据集(附下载链接与避坑指南)

本文精选了5个实战必备的多模态情感分析数据集,包括CMU-MOSEI、CH-SIMS、UR-FUNNY、MUStARD和IEMOCAP,并提供了详细的下载链接与避坑指南。文章重点介绍了如何高效获取、预处理这些数据集,并自然整合了多模态情感分析的核心热词,旨在帮助研究者和开发者快速启动项目,规避常见陷阱,聚焦模型创新。

yolo5detector的博客 280

Ubuntu 22.04下Minkowski Engine编译避坑指南:解决Cuda 12.2与Pytorch cu118版本冲突

本文详细介绍了在Ubuntu 22.04系统中解决Minkowski Engine编译时Cuda 12.2与Pytorch cu118版本冲突的实用方法。通过修改版本检查逻辑、创建兼容符号链接等技巧,帮助开发者顺利完成编译,并提供了性能优化建议和替代方案,确保三维点云处理任务的高效运行。

weixin_42543309的博客 160

Sigrity System SI Parallel Bus Analysis模式进行DDR3仿真分析操作指导-单个颗粒

Default Strobe Offset:DQS默认偏移时间,自动填充为0.5ns,即DQS默认偏移1/2UI,DQS滞后于DQ 1/2UI,让建立保持时间均分。WLO:写平衡偏移的数值,DataL是0ps,DataU是500ps,是根据WLOSkew自动定义的,可以认为是WLOSkew取整,也可以根据需要手动调整数值。注意AddCmd的UI=T,这里的Data Rate仍然是DQ的速率,并不是地址线的速率,地址线的速率=1/UI=1/2ns=0.5Gbps。

weixin_54787054的博客 365

【OpenClaw从入门到精通】第15篇:国产芯片适配实战——昇腾/龙芯/天数智芯全流程跑通(2026实测版)

2026年国产芯片AI适配迎来爆发期,OpenClaw作为轻量化本地AI智能体,已实现华为昇腾、龙芯、天数智芯等主流国产平台的全流程适配。本文基于实测数据,从背景解析、核心原理、算法优化、实操部署四个维度,详细讲解OpenClaw在香橙派昇腾开发板、龙芯3B6000M、天数彤央TY1200及联想开天X7h的部署流程,同时提供统一工具玄武CLI的使用指南。文中包含完整代码、执行结果、避坑技巧及虚拟实战案例,兼顾新手入门与进阶提升,帮助读者快速掌握国产芯片上的本地AI部署能力,实现数据隐私保护与低成本AI落地。

专注于人工智能、软件开发、工控自动化、工厂数字化及智能化等领域,希望和大家共同进步! 1004

TMS_WebGMaps_1.9.8.0_Full_Source

TMS_WebGMaps_1.9.8.0_Full_Source 全源码 delphi cbuilder

IDEA的使用指南

IDEA基于java的使用手册,可以最快速的上手,在使用中不断的丰富自己的使用技巧.

深度学习工具包 DeepLearningToolbox

深度学习工具包Deprecation notice.-----This toolbox is outdated and no longer maintained.There are much better tools available for deep learning than this toolbox, e.g. [Theano](http://deeplearning.net/software/theano/), [torch](http://torch.ch/) or [tensorflow](http://www.tensorflow.org/)I would suggest you use one of the tools mentioned above rather than use this toolbox.Best, Rasmus.DeepLearnToolbox================A Matlab toolbox for Deep Learning.Deep Learning is a new subfield of machine learning that focuses on learning deep hierarchical models of data.It is inspired by the human brain's apparent deep (layered, hierarchical) architecture.A good overview of the theory of Deep Learning theory is[Learning Deep Architectures for AI](http://www.iro.umontreal.ca/~bengioy/papers/ftml_book.pdf)For a more informal introduction, see the following videos by Geoffrey Hinton and Andrew Ng.* [The Next Generation of Neural Networks](http://www.youtube.com/watch?v=AyzOUbkUf3M) (Hinton, 2007)* [Recent Developments in Deep Learning](http://www.youtube.com/watch?v=VdIURAu1-aU) (Hinton, 2010)* [Unsupervised Feature Learning and Deep Learning](http://www.youtube.com/watch?v=ZmNOAtZIgIk) (Ng, 2011)If you use this toolbox in your research please cite [Prediction as a candidate for learning deep hierarchical models of data](http://www2.imm.dtu.dk/pubdb/views/publication_details.php?id=6284)```@MASTERSTHESIS\{IMM2012-06284, author = "R. B. Palm", title = "Prediction as a candidate for learning deep hierarchical models of data", year = "2012",}```Contact: rasmusbergpalm at gmail dot comDirectories included in the toolbox-----------------------------------`NN/` - A library for Feedforward Backpropagation Neural Networks`CNN/` - A library for Convolutional Neural Networks`DBN/` - A library for Deep Belief Networks`SAE/` - A library for Stacked Auto-Encoders`CAE/` - A library for Convolutional Auto-Encoders`util/` - Utility functions used by the libraries`data/` - Data used by the examples`tests/` - unit tests to verify toolbox is workingFor references on each library check REFS.mdSetup-----1. Download.2. addpath(genpath('DeepLearnToolbox'));Example: Deep Belief Network---------------------```matlabfunction test_example_DBNload mnist_uint8;train_x = double(train_x) / 255;test_x = double(test_x) / 255;train_y = double(train_y);test_y = double(test_y);%% ex1 train a 100 hidden unit RBM and visualize its weightsrand('state',0)dbn.sizes = [100];opts.numepochs = 1;opts.batchsize = 100;opts.momentum = 0;opts.alpha = 1;dbn = dbnsetup(dbn, train_x, opts);dbn = dbntrain(dbn, train_x, opts);figure; visualize(dbn.rbm{1}.W'); % Visualize the RBM weights%% ex2 train a 100-100 hidden unit DBN and use its weights to initialize a NNrand('state',0)%train dbndbn.sizes = [100 100];opts.numepochs = 1;opts.batchsize = 100;opts.momentum = 0;opts.alpha = 1;dbn = dbnsetup(dbn, train_x, opts);dbn = dbntrain(dbn, train_x, opts);%unfold dbn to nnnn = dbnunfoldtonn(dbn, 10);nn.activation_function = 'sigm';%train nnopts.numepochs = 1;opts.batchsize = 100;nn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.10, 'Too big error');```Example: Stacked Auto-Encoders---------------------```matlabfunction test_example_SAEload mnist_uint8;train_x = double(train_x)/255;test_x = double(test_x)/255;train_y = double(train_y);test_y = double(test_y);%% ex1 train a 100 hidden unit SDAE and use it to initialize a FFNN% Setup and train a stacked denoising autoencoder (SDAE)rand('state',0)sae = saesetup([784 100]);sae.ae{1}.activation_function = 'sigm';sae.ae{1}.learningRate = 1;sae.ae{1}.inputZeroMaskedFraction = 0.5;opts.numepochs = 1;opts.batchsize = 100;sae = saetrain(sae, train_x, opts);visualize(sae.ae{1}.W{1}(:,2:end)')% Use the SDAE to initialize a FFNNnn = nnsetup([784 100 10]);nn.activation_function = 'sigm';nn.learningRate = 1;nn.W{1} = sae.ae{1}.W{1};% Train the FFNNopts.numepochs = 1;opts.batchsize = 100;nn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.16, 'Too big error');```Example: Convolutional Neural Nets---------------------```matlabfunction test_example_CNNload mnist_uint8;train_x = double(reshape(train_x',28,28,60000))/255;test_x = double(reshape(test_x',28,28,10000))/255;train_y = double(train_y');test_y = double(test_y');%% ex1 Train a 6c-2s-12c-2s Convolutional neural network %will run 1 epoch in about 200 second and get around 11% error. %With 100 epochs you'll get around 1.2% errorrand('state',0)cnn.layers = { struct('type', 'i') %input layer struct('type', 'c', 'outputmaps', 6, 'kernelsize', 5) %convolution layer struct('type', 's', 'scale', 2) %sub sampling layer struct('type', 'c', 'outputmaps', 12, 'kernelsize', 5) %convolution layer struct('type', 's', 'scale', 2) %subsampling layer};cnn = cnnsetup(cnn, train_x, train_y);opts.alpha = 1;opts.batchsize = 50;opts.numepochs = 1;cnn = cnntrain(cnn, train_x, train_y, opts);[er, bad] = cnntest(cnn, test_x, test_y);%plot mean squared errorfigure; plot(cnn.rL);assert(er<0.12, 'Too big error');```Example: Neural Networks---------------------```matlabfunction test_example_NNload mnist_uint8;train_x = double(train_x) / 255;test_x = double(test_x) / 255;train_y = double(train_y);test_y = double(test_y);% normalize[train_x, mu, sigma] = zscore(train_x);test_x = normalize(test_x, mu, sigma);%% ex1 vanilla neural netrand('state',0)nn = nnsetup([784 100 10]);opts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samples[nn, L] = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.08, 'Too big error');%% ex2 neural net with L2 weight decayrand('state',0)nn = nnsetup([784 100 10]);nn.weightPenaltyL2 = 1e-4; % L2 weight decayopts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex3 neural net with dropoutrand('state',0)nn = nnsetup([784 100 10]);nn.dropoutFraction = 0.5; % Dropout fraction opts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex4 neural net with sigmoid activation functionrand('state',0)nn = nnsetup([784 100 10]);nn.activation_function = 'sigm'; % Sigmoid activation functionnn.learningRate = 1; % Sigm require a lower learning rateopts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex5 plotting functionalityrand('state',0)nn = nnsetup([784 20 10]);opts.numepochs = 5; % Number of full sweeps through datann.output = 'softmax'; % use softmax outputopts.batchsize = 1000; % Take a mean gradient step over this many samplesopts.plot = 1; % enable plottingnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex6 neural net with sigmoid activation and plotting of validation and training error% split training data into training and validation datavx = train_x(1:10000,:);tx = train_x(10001:end,:);vy = train_y(1:10000,:);ty = train_y(10001:end,:);rand('state',0)nn = nnsetup([784 20 10]); nn.output = 'softmax'; % use softmax outputopts.numepochs = 5; % Number of full sweeps through dataopts.batchsize = 1000; % Take a mean gradient step over this many samplesopts.plot = 1; % enable plottingnn = nntrain(nn, tx, ty, opts, vx, vy); % nntrain takes validation set as last two arguments (optionally)[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');```[![Bitdeli Badge](https://d2weczhvl823v0.cloudfront.net/rasmusbergpalm/deeplearntoolbox/trend.png)](https://bitdeli.com/free "Bitdeli Badge")

android 蓝牙通讯demo

android 下蓝牙通讯demo,实现了发现蓝牙,使能蓝牙,通过蓝牙发送消息。

上一篇: Introduction to Algorithms 算法导论 第1章 基础知识 学习笔记及习题解答
下一篇: Introduction to Algorithms 算法导论 第3章 函数的增长 学习笔记及习题解答
cppgp
博客等级 码龄20年 47粉丝 46原创
评论 3
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

当前余额3.43元 前往充值 >
需支付:10.00元
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付元
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值