版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/sinat_41144773/article/details/89705423
主要几种排序算法的思维导图
1、直接插入排序
从第一个数开始依次向它的前一个数比较,如果这个数大,则将之前的数向后移位(每次排序会需要移动很多其他的数)
/**
* 直接插入排序的原理
*/
public class InsertSort {
public static void main(String []args){
int[] a = {12,27,5,16,1,85,42,29,6};
insertSort(a);
for(int i = 0; i<a.length; i++){
System.out.println(a[i]);
}
}
public static void insertSort(int[] a){
int insertNum;
for(int i=1;i<a.length;i++){
//当前数insertNum
insertNum=a[i];
//前一个数的索引j
int j=i-1;
//将前面序列比当前数大的所有元素前后移一位
while(j>=0 && a[j]>insertNum){
a[j+1]=a[j];
j--;
}
// 插入当前数
a[j+1]=insertNum;
}
}
}
2、希尔排序
希尔排序是直接插入排序改良的算法,又称缩小增量排序。
- 将数的个数设为n,k=n/2 (k取奇数),将下标差值(增量)为k的数分为一组,分组进行排序。
- (增量缩小)再取k=k/2 (k取奇数),将下标差值为k的数分为一组,分组进行排序。
-
重复第二步,直到k=1,最后执行简单插入排序。
引用:https://www.jianshu.com/p/5e171281a387
//希尔排序
public class ShellSort {
public static void main(String []args){
int[] a = {12,27,5,16,1,85,42,29,6};
sheelSort(a);
for(int i = 0; i<a.length; i++){
System.out.println(a[i]);
}
}
public static void sheelSort(int[] a){
int d = a.length;
while (d!=0) {
d=d/2;
for (int x = 0; x < d; x++) {
for (int i = x + d; i < a.length; i += d) {
int j = i - d;
int temp = a[i];
for (; j >= 0 && temp < a[j]; j -= d) {
a[j + d] = a[j];
}
a[j + d] = temp;
}
}
}
}
}
快速排序和堆排序
详见本篇博客:https://mp.csdn.net/postedit/89439446
几种算法的时间复杂度总结
引用:https://blog.csdn.net/yushiyi6453/article/details/76407640
直接插入排序、冒泡、选择排序,需要两个for循环,平均时间复杂度为O(n的平方)
快速、归并、希尔、堆基于二分思想,log以2为底,平均时间复杂度为O(nlogn)
排序算法的稳定性:排序前后相同元素的相对位置不变。 算法不稳定 “快希选堆”不稳定
未完。。