7大常用排序算法总结

七大排序算法(插排,希尔,选择排序,堆排,冒泡,快排,归并)--图文详解 万字长文加N多图片喂你七大排序的知识点, 让你用脚都能写出排序算法 阅读详情

常用算法总结(包括代码,时间复杂度)

(本文中为从小到大排序)

1、冒泡排序

最常用的排序算法了,从第1个数开始,和下一个数进行比较,假如下一个数小,则交换这两个数的位置,第一趟排序得到数组的最大值,第二趟排序得到次最大值,依次列推,若一趟比较中没有交换,则数组已经正序排列。排序结束。
最好的情况:正序排列,时间复杂度O(n);
最差的情况:逆序排列,时间复杂度O(nn);
平均时间复杂度:O(n
n);

代码如下:

void bubble(int array[],int length)//every time it gets a biggest number
{
	for (int i = 0; i < length-1; i++)
	{
		bool flag = false;
		for (int j = 0; j < length - i-1; j++)
		{
			if (array[j]>array[j + 1])
			{
				swap(array[j], array[j + 1]);
				flag = true;
			}
		}
		if (!flag) break;//假如某次排序没有交换,则说明已经正序
	}
	return;
}

2、选择排序

第一遍从n个数中选出最小的数,记录他的位置,和第一个数交换;然后再n-1个数中选出最小的数,记录位置,和第二个数交换。以此类推,直到最后一个数。
最好的情况,最坏的情况,平均情况:O(n*n);

void select(int array[], int length)
{
	for (int i = 0; i < length-1; i++)
	{
		int  min = i;
		int j = i+1;
		while (j < length)
		{
			if (array[j] < array[min])
			{
				min = j;
			}
			j++;
		}
		if (min != i) swap(array[i], array[min]);
	}
	return;
}

3直接插入排序

直接插入排序就是从第二个数开始,往前插入到合适的位置(如果小于某个位置的数,继续向前,直到大于或等于)。
最好的情况:正序排列O(n);
最坏的情况:逆序排列O(nn);
平均情况:O(n
n);

代码如下:

void insert(int array[], int length)//every time it gets a smallest number
{
	for (int i = 0; i < length-1; i++)
	{
		int j = i;
		int temp = array[i];
		while (j >= 0&&array[j+1]<array[j])
		{
			swap(array[j], array[j + 1]);
			j--;
		}
	}
}

4、快速排序

快排首先需要在数组中随机选一个数,然后把数组分别排列到这个数的两边,大于它的在右边,小于它的在左边,然后再在它的左右两边数组中分别选一个数,继续上面的操作,直到全部数组有序。
最好的情况:正序排列O(nlogn);
最坏的情况:逆序排列O(nn);
平均情况:O(n
logn);

代码如下:

int oncesort(int array[], int start, int end)//choose the number at end and sort the two groups of numbers
{
	if (start > end||start<0) return -1;
	int small = start - 1;
	for (int index = start; index < end; index++)
	{
		if (array[index] < array[end])
		{
			small++;
			if (small != index)
				swap(array[index], array[small]);
		}
	}
	small++;
	swap(array[small], array[end]);
	return small;
	
}
void quick(int array[], int start,int end)
{
	if (start == end) return;
	int index = oncesort(array,start,end);
	if (index > start) quick(array, start, index-1);
	if (index < end) quick(array, index + 1, end);
	return;
}

5、希尔排序

也是一种选择排序,但是是分区域来进行排序,先选择一个增量,对对应的增量进行排序,然后逐步减小增量,直到最后增量为1时,几乎已经是排好序的序列了。
最好的情况:O(nlogn);
最坏的情况:O(nlogn);
平均情况:O(n*logn);

代码如下:

void herl(int array[], int length)
{
	if (length < 0) return;
	
	for (int add = length / 2; add > 0; add = add / 2)
	{
		for (int i = 0; i + add < length; i++)
		{
			if (array[i]>array[i + add])
				swap(array[i], array[i + add]);
		}
	}
	return;
}

6、归并排序

归并排序和快排类似,不过归并排序是把数组直接分成前后两个部分进行排序,然后前后两个数组再继续分成两个数组,直到有序。每次排好的部分按顺序放进一个新的数组中,最后把这个数组一一赋值出传递给原数组得到有序数组。
最好的情况:O(nlogn);
最坏的情况:O(nlogn);
平均情况:O(n*logn);

代码如下:

void mergetwo(int array[], int start, int mid,int end, int *temp)
{
	int k = start;
	int i = start, j = mid + 1;
	while ( i <= mid&&j <= end)
	{
		if (array[i] <= array[j])
		{
			temp[k++] = array[i++];
		}
		else
			temp[k++] = array[j++];
	}
	while (i <= mid) temp[k++] = array[i++]; 
	while (j <= end) temp[k++] = array[j++];
	for (int i = start; i <= end; i++)
	{
		array[i] = temp[i];
	}
}
void mergecore(int array[], int start, int end, int *temp)
{
	if (start >= end) return;
	int mid = (end + start) / 2;
	
	mergecore(array, start, mid, temp);
	mergecore(array, mid + 1, end, temp); 
	mergetwo(array, start, mid, end, temp); 
	return;
}
void merge(int array[], int length)
{
	if (length<1) return;
	int *temp = new int[length]();
	int start = 0;
	int  end = length - 1;
	mergecore(array, start, end, temp);
	show(array, length);
	delete[]temp;
}

7、堆排序

堆排序首先需要把数组建立成一个最大堆,然后交换堆顶和堆的最后一个数,然后去掉最后一个数,继续调整数组为最大堆,再交换堆顶和堆的最后一个数,直到数组有序。
最好的情况:O(nlogn);
最坏的情况:O(nlogn);
平均情况:O(n*logn);

代码如下:

void maxheap(int array[], int start, int end)
{
	int dad = start;
	int son = 2 * dad + 1;
	while (son <= end)
	{
		if (son + 1 <= end&&array[son] < array[son + 1])
			son++;
		if (array[dad] > array[son])
			return;
		else
			swap(array[son], array[dad]);
		dad = son;
		son = dad * 2 + 1;
	}
}
void heap(int array[], int length)
{
	for (int i = length / 2 - 1; i >= 0; i--)
		maxheap(array, i, length - 1);
	for (int i = length - 1; i > 0; i--)
	{
		swap(array[0], array[i]);
		maxheap(array, 0, i-1);
	}
	return;
}
【数据结构】常见七大排序总结 常见七大排序概念算法总结 阅读详情

相关推荐

常见六种排序算法的实现

1、插入排序 2、shell排序 3、堆排序 4、冒泡排序 5、快速排序 6、归并排序

七大排序,你都搞懂了几个

一、冒泡排序 1.1 冒泡排序一般写法 冒泡排序就是将相邻的两个数字比较,如果顺序错误就将两个数交换,每轮遍历后右侧位置为最大值。 public void bubbleSort(int[] arr){ for (int i = 0; i <arr.length ; i++) { //每轮遍历后,第arr.length-i-1之后的元素都有序了,不用比较 //减少程序运行次数 for (int j = 0; j < a

m0_49622667的博客 469

Ubuntu终端一键安装英伟达驱动:无需手动下载的完整指南

本文提供了一份在Ubuntu系统上通过终端命令一键安装英伟达显卡驱动的完整指南。该方法利用官方PPA源,无需手动下载驱动文件,可自动检测硬件并安装最佳版本,极大简化了流程,适合深度学习环境搭建等场景,有效提升安装效率与稳定性。

weixin_29232121的博客 180

七大排序(插入排序,希尔排序,选择排序,堆排序,冒泡排序,快速排序,归并排序)

七大排序(插入排序,希尔排序,选择排序,堆排序,冒泡排序,快速排序,归并排序) 1.插入排序:把待排序的记录按其关键码值的大小逐个插入到一个已经排好序的有序序列中,直到所有的记录插入完为止,得到一个新的有序序列 。 2.希尔排序:先选定一个整数,把待排序文件中所有记录分成gap/2个组,所有距离为的记录分在同一组内,并对每一组内的记录进行排序。然后取,重复上述分组和排序的工作。当到达gap...

gp1330782530的博客 3185

金蝶云星空核心数据表解析与高效关联查询指南

本文深入解析金蝶云星空核心数据表结构,提供高效关联查询的实战指南。文章详细介绍了基础资料、业务单据和财务模块的关键表及其关联逻辑,重点阐述了如何利用关联表(_LK表)进行跨单据溯源,并分享了编写高性能SQL的实用技巧与避坑建议,帮助开发者、实施顾问和数据分析师快速掌握数据查询方法,提升工作效率。

weixin_29254673的博客 526

数学建模——相关系数(4)——斯皮尔曼相关系数(spearman)

文章目录引述斯皮尔曼相关系数(spearman)定义 引述 经过之前几节的学习,我们了解并掌握了皮尔逊相关系数。在学习中我们发现,皮尔逊相关系数的使用条件相当苛刻:两组变量必须是连续数据、呈现正态分布,且两者间必须成线性关系。如果我们在数学建模中拿到一组数据无法满足以上条件,那么有没有其他的方法去判断两组变量之间的相关性呢?答案是肯定的,它就是斯皮尔曼相关系数(spearman). 斯皮尔曼相关系...

东 6万+

常用十大排序算法

列举了常见的十大内部排序算法:插入排序、希尔排序、选择排序、冒泡排序、归并排序、快速排序、堆排序、基数排序,计数排序,桶排序。

qq_51664685的博客 15万+

适配adv7280m相机到rk3588的安卓平台

Kernel-5.10/arch/arm64/configs/firefly_defconfig里面增加配置CONFIG_VIDEO_ADV7180=y。出现一次开不了机器的情况,接调试口发现,在set_fmt里面用s_ctrl对mipi的频率进行设置会出现异常。设备树修改kernel-5.10/arch/arm64/boot/dts/rockchip/13.dts。把MEDIA_ENT_F_ATV_DECODER改回MEDIA_ENT_F_CAM_SENSOR。第二次编译,仅仅刷新boot.img。

chenyq14的专栏 2449

java常用的7大排序算法汇总

这段时间闲了下来,就抽了点时间总结了下java中常用的七大排序算法,希望以后可以回顾!

文艺范Coder的博客,5星好评哦亲~ 1655

AI 生成 CAN 通信测试用例实战

本文分享了AI辅助汽车电子测试用例编写的实战经验。通过某车企CAN网络测试项目案例,对比传统方式(需27天)与AI辅助方式(仅5天)的效率差异,展示81%的效率提升。文章详细介绍了从DBC文件提取信号信息的方法,包括DBC文件结构解析、信号定义说明,并提供了完整的Python解析脚本代码,可将信号信息导出为JSON或Excel格式,为后续AI批量生成测试用例奠定基础。

小明的博客 694

宇树科技嵌入式面试题及参考答案(春晚机器人的公司)

内存对齐是指在内存中为数据对象分配存储空间时,按照一定的规则将数据存储在特定的地址上,以提高内存访问效率。不同的数据类型在内存中都有其特定的对齐要求,例如,int类型通常要求 4 字节对齐,double类型通常要求 8 字节对齐。这意味着数据的存储地址必须是其对齐字节数的整数倍。如果不进行内存对齐,处理器在访问数据时可能需要进行多次内存访问,从而降低了访问效率。指令可以用于控制结构体内存布局,它允许程序员指定结构体成员的对齐方式。其基本用法是在结构体定义之前使用来指定对齐字节数n,其中n。

大模型大数据攻城狮的专栏 3227

java常用的算法_java常用的7大排序算法汇总

这段时间闲了下来,就抽了点时间总结了下java中常用的七大排序算法,希望以后可以回顾!1.插入排序算法插入排序的基本思想是在遍历数组的过程中,假设在序号 i 之前的元素即 [0..i-1] 都已经排好序,本趟需要找到 i 对应的元素 x 的正确位置 k ,并且在寻找这个位置 k 的过程中逐个将比较过的元素往后移一位,为元素 x “腾位置”,***将 k 对应的元素值赋为 x ,一般情况下,插入排序...

weixin_39844481的博客 326

NX二次开发 内部函数鼠标动态位置获取

内部函数鼠标动态位置获取

qq285503851的博客 3337

Java常用的7大排序算法汇总

转载:原文地址:http://mp.weixin.qq.com/s?__biz=MjM5MDI5MjAyMA==&mid=400489561&idx=2&sn=7f6d76bc1e6aee46d88a078d77805b33&scene=23&srcid=1120hV85iVy8oxk2sqqCoXvf#rd 这段时间闲了下来,就抽了点时间总结了下java中常用的七大排序算法,希

Spring cloud 超时汇总 498

手把手教你学Simulink——基于Simulink的电压型 vs 电流型整流器性能对比

摘要:本文基于Simulink平台对比分析了电压型整流器(VSR)和电流型整流器(CSR)的性能差异。VSR采用电容滤波,具有高功率因数(PF>0.99)、低输入电流THD(<3%)等优势,但动态响应较慢;CSR采用电感滤波,动态响应快(<0.05s),但THD较高(5%~8%)。研究建立了统一测试平台,详细对比了两者在稳态性能、动态响应、效率等方面的差异,并给出了控制算法实现和参数优化建议。通过量化分析,为电力电子工程师提供了拓扑选型依据,可根据恒压/恒流需求选择最优方案,有效缩短开发周

MHD0815的博客 173

VC中sqlite的使用

在VC中对sqlite的使用,实现数据库大批数据的快速插入,读取数据库中的数据在ListCtrl中显示

常用的7大排序算法汇总

2019独角兽企业重金招聘Python工程师标准>>> ...

weixin_34050005的博客 74

深度学习工具包 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")

上一篇: 回文字符串判断以及最长回文字符串长度判断
下一篇: 大数相乘和相加(当长整形都表示不了这个整数时,该如何进行计算呢?)
vanvanvane
博客等级 码龄7年 1粉丝 7原创
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

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

抵扣说明:

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

余额充值