比较
名称 | 数据对象 | 稳定性 | 时间复杂度 | 额外空间复杂度 | 描述 | |
---|---|---|---|---|---|---|
平均 | 最坏 | |||||
冒泡排序 | 数组 | {\displaystyle O(n^{2})} | {\displaystyle O(1)} | (无序区,有序区)。 从无序区通过交换找出最大元素放到有序区前端。 | ||
选择排序 | 数组 | {\displaystyle O(n^{2})} | {\displaystyle O(1)} | (有序区,无序区)。 在无序区里找一个最小的元素跟在有序区的后面。对数组:比较得多,换得少。 | ||
链表 | ||||||
插入排序 | 数组、链表 | {\displaystyle O(n^{2})} | {\displaystyle O(1)} | (有序区,无序区)。 把无序区的第一个元素插入到有序区的合适的位置。对数组:比较得少,换得多。 | ||
堆排序 | 数组 | {\displaystyle O(n\log n)} | {\displaystyle O(1)} | (最大堆,有序区)。 从堆顶把根卸出来放在有序区之前,再恢复堆。 | ||
归并排序 | 数组 | {\displaystyle O(n\log ^{2}n)} | {\displaystyle O(1)} | 把数据分为两段,从两段中逐个选最小的元素移入新数据段的末尾。 可从上到下或从下到上进行。 | ||
{\displaystyle O(n\log n)} | {\displaystyle O(n)+O(\log n)} 如果不是从下到上 | |||||
链表 | {\displaystyle O(1)} | |||||
快速排序 | 数组 | {\displaystyle O(n\log n)} | {\displaystyle O(n^{2})} | {\displaystyle O(\log n)} | (小数,基准元素,大数)。 在区间中随机挑选一个元素作基准,将小于基准的元素放在基准之前,大于基准的元素放在基准之后,再分别对小数区与大数区进行排序。 | |
希尔排序 | 数组 | {\displaystyle O(n\log ^{2}n)} | {\displaystyle O(n^{2})} | {\displaystyle O(1)} | 每一轮按照事先决定的间隔进行插入排序,间隔会依次缩小,最后一次一定要是1。 | |
计数排序 | 数组、链表 | {\displaystyle O(n+m)} | {\displaystyle O(n+m)} | 统计小于等于该元素值的元素的个数i,于是该元素就放在目标数组的索引i位(i≥0)。 | ||
桶排序 | 数组、链表 | {\displaystyle O(n)} | {\displaystyle O(m)} | 将值为i的元素放入i号桶,最后依次把桶里的元素倒出来。 | ||
基数排序 | 数组、链表 | {\displaystyle O(k\times n)} | {\displaystyle O(n^{2})} | 一种多关键字的排序算法,可用桶排序实现。 |
希尔排序
定义
- 插入排序在对几乎已经排好序的数据操作时,效率高,即可以达到线性排序的效率。
- 但插入排序一般来说是低效的,因为插入排序每次只能将数据移动一位。
基本思想
代码实现
/*
* 希尔排序
*/
public class ShellSort {
/**
* 排序方法
*/
public static void sort(long[] arr) {
//初始化一个间隔
int h = 1;
//计算最大间隔
while(h < arr.length / 3) {
h = h * 3 + 1;
}
while(h > 0) {
//进行插入排序
long tmp = 0;
for(int i = h; i < arr.length; i++) {
tmp = arr[i];
int j = i;
while(j > h - 1 && arr[j - h] >= tmp) {
arr[j] = arr[j - h];
j -= h;
}
arr[j] = tmp;
}
//减小间隔
h = (h - 1) / 3;
}
}
}
快速排序
简介
思路分析
下标 | 0 | 1 | 2 | 3 | 4 | 5 |
数据 | 6 | 2 | 7 | 3 | 8 | 9 |
下标 | 0 | 1 | 2 | 3 | 4 | 5 |
数据 | 3 | 2 | 7 | 6 | 8 | 9 |
下标 | 0 | 1 | 2 | 3 | 4 | 5 |
数据 | 3 | 2 | 6 | 7 | 8 | 9 |
下标 | 0 | 1 | 2 | 3 | 4 | 5 |
数据 | 3 | 2 | 6 | 7 | 8 | 9 |
代码实现
/*
* 快速排序
*/
public class QuickSort {
/**
* 划分数组
*/
public static int partition(long arr[],int left, int right,long point) {
int leftPtr = left - 1;
int rightPtr = right;
while(true) {
//循环,将比关键字小的留在左端
while(leftPtr < rightPtr && arr[++leftPtr] < point);
//循环,将比关键字大的留在右端
while(rightPtr > leftPtr && arr[--rightPtr] > point);
if(leftPtr >= rightPtr) {
break;
} else {
long tmp = arr[leftPtr];
arr[leftPtr] = arr[rightPtr];
arr[rightPtr] = tmp;
}
}
//将关键字和当前leftPtr所指的这一个进行交换
long tmp = arr[leftPtr];
arr[leftPtr] = arr[right];
arr[right] = tmp;
return leftPtr;
}
public static void sort(long[] arr, int left, int right) {
if(right - left <= 0) {
return;
} else {
//设置关键字
long point = arr[right];
//获得切入点,同时对数组进行划分
int partition = partition(arr, left, right, point);
//对左边的子数组进行快速排序
sort(arr,left,partition - 1);
//对右边的子数组进行快速排序
sort(arr,partition + 1, right);
}
}
}