八种经典排序算法总结,妈妈再也不用担心我不会了
myzbx 2025-07-02 23:17 11 浏览
前言
算法和数据结构是一个程序员的内功,所以经常在一些笔试中都会要求手写一些简单的排序算法,以此考验面试者的编程水平。下面我就简单介绍八种常见的排序算法,一起学习一下。
一、冒泡排序
思路:
- 比较相邻的元素。如果第一个比第二个大,就交换它们两个;
- 对每一对相邻元素作同样的工作,从开始第一对到结尾的最后一对,这样在最后的元素就是最大的数;
- 排除最大的数,接着下一轮继续相同的操作,确定第二大的数...
- 重复步骤1-3,直到排序完成。
动画演示:
实现代码:
/**
* @author Ye Hongzhi 公众号:java技术爱好者
* @name BubbleSort
* @date 2020-09-05 21:38
**/
public class BubbleSort extends BaseSort {
public static void main(String[] args) {
BubbleSort sort = new BubbleSort();
sort.printNums();
}
@Override
protected void sort(int[] nums) {
if (nums == null || nums.length < 2) {
return;
}
for (int i = 0; i < nums.length - 1; i++) {
for (int j = 0; j < nums.length - i - 1; j++) {
if (nums[j] > nums[j + 1]) {
int temp = nums[j];
nums[j] = nums[j + 1];
nums[j + 1] = temp;
}
}
}
}
}
//10万个数的数组,耗时:21554毫秒
平均时间复杂度:O(n^2)
空间复杂度:O(1)
算法稳定性:稳定
二、插入排序
思路:
- 从第一个元素开始,该元素可以认为已经被排序;
- 取出下一个元素,在前面已排序的元素序列中,从后向前扫描;
- 如果该元素(已排序)大于新元素,将该元素移到下一位置;
- 重复步骤3,直到找到已排序的元素小于或者等于新元素的位置;
- 将新元素插入到该位置后;
- 重复步骤2~5。
动画演示:
实现代码:
/**
* @author Ye Hongzhi 公众号:java技术爱好者
* @name InsertSort
* @date 2020-09-05 22:34
**/
public class InsertSort extends BaseSort {
public static void main(String[] args) {
BaseSort sort = new InsertSort();
sort.printNums();
}
@Override
protected void sort(int[] nums) {
if (nums == null || nums.length < 2) {
return;
}
for (int i = 0; i < nums.length - 1; i++) {
//当前值
int curr = nums[i + 1];
//上一个数的指针
int preIndex = i;
//在数组中找到一个比当前遍历的数小的第一个数
while (preIndex >= 0 && curr < nums[preIndex]) {
//把比当前遍历的数大的数字往后移动
nums[preIndex + 1] = nums[preIndex];
//需要插入的数的下标往前移动
preIndex--;
}
//插入到这个数的后面
nums[preIndex + 1] = curr;
}
}
}
//10万个数的数组,耗时:2051毫秒
平均时间复杂度:O(n^2)
空间复杂度:O(1)
算法稳定性:稳定
三、选择排序
思路:
第一轮,找到最小的元素,和数组第一个数交换位置。
第二轮,找到第二小的元素,和数组第二个数交换位置...
直到最后一个元素,排序完成。
动画演示:
实现代码:
/**
* @author Ye Hongzhi 公众号:java技术爱好者
* @name SelectSort
* @date 2020-09-06 22:27
**/
public class SelectSort extends BaseSort {
public static void main(String[] args) {
SelectSort sort = new SelectSort();
sort.printNums();
}
@Override
protected void sort(int[] nums) {
for (int i = 0; i < nums.length; i++) {
int minIndex = i;
for (int j = i + 1; j < nums.length; j++) {
if (nums[j] < nums[minIndex]) {
minIndex = j;
}
}
if (minIndex != i) {
int temp = nums[i];
nums[minIndex] = temp;
nums[i] = nums[minIndex];
}
}
}
}
//10万个数的数组,耗时:8492毫秒
算法复杂度:O(n^2)
算法空间复杂度:O(1)
算法稳定性:不稳定
四、希尔排序
思路:
把数组分割成若干(h)个小组(一般数组长度length/2),然后对每一个小组分别进行插入排序。每一轮分割的数组的个数逐步缩小,h/2->h/4->h/8,并且进行排序,保证有序。当h=1时,则数组排序完成。
动画演示:
实现代码:
/**
* @author Ye Hongzhi 公众号:java技术爱好者
* @name SelectSort
* @date 2020-09-06 22:27
**/
public class ShellSort extends BaseSort {
public static void main(String[] args) {
ShellSort sort = new ShellSort();
sort.printNums();
}
@Override
protected void sort(int[] nums) {
if (nums == null || nums.length < 2) {
return;
}
int length = nums.length;
int temp;
//步长
int gap = length / 2;
while (gap > 0) {
for (int i = gap; i < length; i++) {
temp = nums[i];
int preIndex = i - gap;
while (preIndex >= 0 && nums[preIndex] > temp) {
nums[preIndex + gap] = nums[preIndex];
preIndex -= gap;
}
nums[preIndex + gap] = temp;
}
gap /= 2;
}
}
}
//10万个数的数组,耗时:261毫秒
算法复杂度:O(nlog2n)
算法空间复杂度:O(1)
算法稳定性:稳定
五、快速排序
快排,面试最喜欢问的排序算法。这是运用分治法的一种排序算法。
思路:
- 从数组中选一个数作为基准值,一般选第一个数,或者最后一个数。
- 采用双指针(头尾两端)遍历,从左往右找到比基准值大的第一个数,从右往左找到比基准值小的第一个数,交换两数位置,直到头尾指针相等或头指针大于尾指针,把基准值与头指针的数交换。这样一轮之后,左边的数就比基准值小,右边的数就比基准值大。
- 对左边的数列,重复上面1,2步骤。对右边重复1,2步骤。
- 左右两边数列递归结束后,排序完成。
动画演示:
实现代码:
/**
* @author Ye Hongzhi 公众号:java技术爱好者
* @name SelectSort
* @date 2020-09-06 22:27
**/
public class QuickSort extends BaseSort {
public static void main(String[] args) {
QuickSort sort = new QuickSort();
sort.printNums();
}
@Override
protected void sort(int[] nums) {
if (nums == null || nums.length < 2) {
return;
}
quickSort(nums, 0, nums.length - 1);
}
private void quickSort(int[] nums, int star, int end) {
if (star > end) {
return;
}
int i = star;
int j = end;
int key = nums[star];
while (i < j) {
while (i < j && nums[j] > key) {
j--;
}
while (i < j && nums[i] <= key) {
i++;
}
if (i < j) {
int temp = nums[i];
nums[i] = nums[j];
nums[j] = temp;
}
}
nums[star] = nums[i];
nums[i] = key;
quickSort(nums, star, i - 1);
quickSort(nums, i + 1, end);
}
}
//10万个数的数组,耗时:50毫秒
算法复杂度:O(nlogn)
算法空间复杂度:O(1)
算法稳定性:不稳定
六、归并排序
归并排序是采用分治法的典型应用,而且是一种稳定的排序方式,不过需要使用到额外的空间。
思路:
- 把数组不断划分成子序列,划成长度只有2或者1的子序列。
- 然后利用临时数组,对子序列进行排序,合并,再把临时数组的值复制回原数组。
- 反复操作1~2步骤,直到排序完成。
归并排序的优点在于最好情况和最坏的情况的时间复杂度都是O(nlogn),所以是比较稳定的排序方式。
动画演示:
实现代码:
/**
* @author Ye Hongzhi 公众号:java技术爱好者
* @name MergeSort
* @date 2020-09-08 23:30
**/
public class MergeSort extends BaseSort {
public static void main(String[] args) {
MergeSort sort = new MergeSort();
sort.printNums();
}
@Override
protected void sort(int[] nums) {
if (nums == null || nums.length < 2) {
return;
}
//归并排序
mergeSort(0, nums.length - 1, nums, new int[nums.length]);
}
private void mergeSort(int star, int end, int[] nums, int[] temp) {
//递归终止条件
if (star >= end) {
return;
}
int mid = star + (end - star) / 2;
//左边进行归并排序
mergeSort(star, mid, nums, temp);
//右边进行归并排序
mergeSort(mid + 1, end, nums, temp);
//合并左右
merge(star, end, mid, nums, temp);
}
private void merge(int star, int end, int mid, int[] nums, int[] temp) {
int index = 0;
int i = star;
int j = mid + 1;
while (i <= mid && j <= end) {
if (nums[i] > nums[j]) {
temp[index++] = nums[j++];
} else {
temp[index++] = nums[i++];
}
}
while (i <= mid) {
temp[index++] = nums[i++];
}
while (j <= end) {
temp[index++] = nums[j++];
}
//把临时数组中已排序的数复制到nums数组中
if (index >= 0) System.arraycopy(temp, 0, nums, star, index);
}
}
//10万个数的数组,耗时:26毫秒
算法复杂度:O(nlogn)
算法空间复杂度:O(n)
算法稳定性:稳定
七、堆排序
大顶堆概念:每个节点的值都大于或者等于它的左右子节点的值,所以顶点的数就是最大值。
思路:
- 对原数组构建成大顶堆。
- 交换头尾值,尾指针索引减一,固定最大值。
- 重新构建大顶堆。
- 重复步骤2~3,直到最后一个元素,排序完成。
构建大顶堆的思路,可以看代码注释。
动画演示:
实现代码:
/**
* @author Ye Hongzhi 公众号:java技术爱好者
* @name HeapSort
* @date 2020-09-08 23:34
**/
public class HeapSort extends BaseSort {
public static void main(String[] args) {
HeapSort sort = new HeapSort();
sort.printNums();
}
@Override
protected void sort(int[] nums) {
if (nums == null || nums.length < 2) {
return;
}
heapSort(nums);
}
private void heapSort(int[] nums) {
if (nums == null || nums.length < 2) {
return;
}
//构建大根堆
createTopHeap(nums);
int size = nums.length;
while (size > 1) {
//大根堆的交换头尾值,固定最大值在末尾
swap(nums, 0, size - 1);
//末尾的索引值往左减1
size--;
//重新构建大根堆
updateHeap(nums, size);
}
}
private void createTopHeap(int[] nums) {
for (int i = 0; i < nums.length; i++) {
//当前插入的索引
int currIndex = i;
//父节点的索引
int parentIndex = (currIndex - 1) / 2;
//如果当前遍历的值比父节点大的话,就交换值。然后继续往上层比较
while (nums[currIndex] > nums[parentIndex]) {
//交换当前遍历的值与父节点的值
swap(nums, currIndex, parentIndex);
//把父节点的索引指向当前遍历的索引
currIndex = parentIndex;
//往上计算父节点索引
parentIndex = (currIndex - 1) / 2;
}
}
}
private void updateHeap(int[] nums, int size) {
int index = 0;
//左节点索引
int left = 2 * index + 1;
//右节点索引
int right = 2 * index + 2;
while (left < size) {
//最大值的索引
int largestIndex;
//如果右节点大于左节点,则最大值索引指向右子节点索引
if (right < size && nums[left] < nums[right]) {
largestIndex = right;
} else {
largestIndex = left;
}
//如果父节点大于最大值,则把父节点索引指向最大值索引
if (nums[index] > nums[largestIndex]) {
largestIndex = index;
}
//如果父节点索引指向最大值索引,证明已经是大根堆,退出循环
if (largestIndex == index) {
break;
}
//如果不是大根堆,则交换父节点的值
swap(nums, largestIndex, index);
//把最大值的索引变成父节点索引
index = largestIndex;
//重新计算左节点索引
left = 2 * index + 1;
//重新计算右节点索引
right = 2 * index + 2;
}
}
private void swap(int[] nums, int i, int j) {
int temp = nums[i];
nums[i] = nums[j];
nums[j] = temp;
}
}
//10万个数的数组,耗时:38毫秒
算法复杂度:O(nlogn)
算法空间复杂度:O(1)
算法稳定性:不稳定
八、桶排序
思路:
- 找出最大值,最小值。
- 根据数组的长度,创建出若干个桶。
- 遍历数组的元素,根据元素的值放入到对应的桶中。
- 对每个桶的元素进行排序(可使用快排,插入排序等)。
- 按顺序合并每个桶的元素,排序完成。
对于数组中的元素分布均匀的情况,排序效率较高。相反的,如果分布不均匀,则会导致大部分的数落入到同一个桶中,使效率降低。
动画演示(来源于五分钟学算法,侵删):
实现代码:
/**
* @author Ye Hongzhi 公众号:java技术爱好者
* @name BucketSort
* @date 2020-09-08 23:37
**/
public class BucketSort extends BaseSort {
public static void main(String[] args) {
BucketSort sort = new BucketSort();
sort.printNums();
}
@Override
protected void sort(int[] nums) {
if (nums == null || nums.length < 2) {
return;
}
bucketSort(nums);
}
public void bucketSort(int[] nums) {
if (nums == null || nums.length < 2) {
return;
}
//找出最大值,最小值
int max = Integer.MIN_VALUE;
int min = Integer.MAX_VALUE;
for (int num : nums) {
min = Math.min(min, num);
max = Math.max(max, num);
}
int length = nums.length;
//桶的数量
int bucketCount = (max - min) / length + 1;
int[][] bucketArrays = new int[bucketCount][];
//遍历数组,放入桶内
for (int i = 0; i < length; i++) {
//找到桶的下标
int index = (nums[i] - min) / length;
//添加到指定下标的桶里,并且使用插入排序排序
bucketArrays[index] = insertSortArrays(bucketArrays[index], nums[i]);
}
int k = 0;
//合并全部桶的
for (int[] bucketArray : bucketArrays) {
if (bucketArray == null || bucketArray.length == 0) {
continue;
}
for (int i : bucketArray) {
//把值放回到nums数组中
nums[k++] = i;
}
}
}
//每个桶使用插入排序进行排序
private int[] insertSortArrays(int[] arr, int num) {
if (arr == null || arr.length == 0) {
return new int[]{num};
}
//创建一个temp数组,长度是arr数组的长度+1
int[] temp = new int[arr.length + 1];
//把传进来的arr数组,复制到temp数组
for (int i = 0; i < arr.length; i++) {
temp[i] = arr[i];
}
//找到一个位置,插入,形成新的有序的数组
int i;
for (i = temp.length - 2; i >= 0 && temp[i] > num; i--) {
temp[i + 1] = temp[i];
}
//插入需要添加的值
temp[i + 1] = num;
//返回
return temp;
}
}
//10万个数的数组,耗时:8750毫秒
算法复杂度:O(M+N)
算法空间复杂度:O(M+N)
算法稳定性:稳定(取决于桶内的排序算法,这里使用的是插入排序所以是稳定的)。
总结
讲完这些排序算法后,可能有人会问学这些排序算法有什么用呢,难道就为了应付笔试面试?平时开发也没用得上这些。
我觉得我们应该换个角度来看,比如高中时我们学物理,化学,数学,那么多公式定理,现在也没怎么用得上,但是高中课本为什么要教这些呢?
我的理解是:第一,普及一些常识性的问题。第二,锻炼思维,提高解决问题的能力。第三,为了区分人才。
回到学排序算法有什么用的问题上,实际上也一样。这些最基本的排序算法就是一些常识性的问题,作为开发者应该了解掌握。同时也锻炼了编程思维,其中包含有双指针,分治,递归等等的思想。最后在面试中体现出来的就是人才的划分,懂得这些基本的排序算法当然要比不懂的人要更有竞争力。
建议大家看完之后,能找时间动手写一下,加深理解。
本文为阿里云原创内容,未经允许不得转载。
相关推荐
- 掌握JavaScript中的Call和Apply,让你的代码更强大、更灵活
-
在学习JavaScript时,你可能会遇到call和apply这两个方法。它们的作用其实很相似,都是用来调用函数并设置函数内部的this值,但它们的使用方式稍有不同。想象一下,你和朋友们一起拍照。ca...
- 性能调优方面,经常要优化跑的最慢的代码,教你一种快速的方法
-
在我们遇到性能问题的时候,很多时候需要去查看性能的瓶颈在哪里,本篇文章就是提供了多种常用的方案来监控函数的运行时间。1.time首先说明,time模块很多是系统相关的,在不同的OS中可能会有一些精度差...
- call和apply的实现方式_call和apply用法
-
call和apply的实现方式1、函数Function.call()的实现//第一步简单是实现call()varfoo={value:”1”,bar:function(){conso...
- 线上问题排查:接口超时_接口超时时间设置多少合适
-
最近就看到了一个非常厉害的关于“接口超时”问题排查的帖子,从应用排查到内核级别。虽然看到后面的时候我已经有点跟不上了,但是对于整个问题排查的过程还是比较清晰的。(细节不重要,排查思路,方向值得学习)问...
- javascript中的call方法的另一种实现方式-更接近原方法
-
上集我们说到对应的我们自己实现的call方法还是有一点纰漏,这里我们就解决它//一、预备知识(简单介绍)//1、Function.prototype.call()//语法:function....
- 链接器是如何一步步发明出来的?_如何使用连接器
-
在计算机编程的早期年代,你面临一个挥之不去的的噩梦。。。你找了一个刚刚运行成功的程序仔细看了看:; main.asm - 主程序start: &nb...
- Day59:回调(callback)函数_回调 callback
-
定义Acallbackisafunctionthatispassedasanargumenttoanotherfunctionandisexecutedafteri...
- 大促数据库压力激增,如何一眼定位 SQL 执行来源?
-
作者:京东科技王奕龙你是否曾经遇到过这样的情况:在大促活动期间,用户访问量骤增,数据库的压力陡然加大,导致响应变慢甚至服务中断?更让人头疼的是,当你试图快速定位问题所在时,却发现难以确定究竟是哪个业...
- 一键追欠料!WPS表格实战MRP欠料计算-7
-
昨天第6章内容主要聚焦于本报表的核心欠料运算。通过子件库存的引用以及累计需求的计算,计算出了子件的累计欠料。累计欠料的显示方式是按日期进行逐日累加,并不能清晰的看到每张订单欠料多少?所以在今日第7章的...
- Python教程(二十五):装饰器–函数的高级用法
-
今天您将学习什么什么是装饰器以及如何创建装饰器函数装饰器和类装饰器带参数的装饰器装饰器的实际应用真实世界示例:日志记录、性能监控、缓存、权限验证什么是装饰器?装饰器是Python中的一种...
- 在 Excel 日历制作中,尤其是动态日历方案,会用到的多个函数详解
-
在Excel日历制作中,尤其是动态日历方案,会用到多个核心函数。下面我将详细解析这些函数的作用、参数和使用技巧:核心日期函数1.DATE(year,month,day)作用:创建指定日期参...
- java高级用法之:在JNA中将本地方法映射到JAVA代码中
-
简介不管是JNI还是JNA,最终调用的都是native的方法,但是对于JAVA程序来说,一定需要一个调用native方法的入口,也就是说我们需要在JAVA方法中定义需要调用的native方法。对于JN...
- 14.4 查找与引用函数综合应用 - 下
-
一、使返回错误值以简化公式例提取一二三级科目名称在下图所示的科目代码表中,A列为科目代码,B列为对应科目名称。A列科目代码中长度为4的为一级代码,长度为6的为二级代码,长度为8的为三级代码。要求根据...
- 记一次酣畅淋漓的JavaScript逆向_js逆向webpack
-
背景介绍今天在写爬虫的练习题时遇到了这样一个难题:目标资源是一个图片的url,但是不同于以往的情况,我在http响应记录里搜索这个图片的url,发现并不能搜到。从逻辑上来讲,这个url被展示到浏览器上...
- 「Postman」测试(Tests)脚本编写和断言详解
-
测试确认您的API按预期工作,服务之间的集成运行可靠,并且新开发没有破坏任何现有功能。您可以使用JavaScript为PostmanAPI请求编写测试脚本。当您的API项目出现问题时...
- 一周热门
- 最近发表
- 标签列表
-
- HTML 简介 (30)
- HTML 响应式设计 (31)
- HTML URL 编码 (32)
- HTML Web 服务器 (31)
- HTML 表单属性 (32)
- HTML 音频 (31)
- HTML5 支持 (33)
- HTML API (36)
- HTML 总结 (32)
- HTML 全局属性 (32)
- HTML 事件 (31)
- HTML 画布 (32)
- HTTP 方法 (30)
- 键盘快捷键 (30)
- CSS 语法 (35)
- CSS 轮廓宽度 (31)
- CSS 谷歌字体 (33)
- CSS 链接 (31)
- CSS 定位 (31)
- CSS 图片库 (32)
- CSS 图像精灵 (31)
- SVG 文本 (32)
- 时钟启动 (33)
- HTML 游戏 (34)
- JS Loop For (32)