几种常见的排序算法(插入排序,希尔排序,归并排序和快速排序),算法分析以及改进

来源:互联网 发布:网站用户数据分析 编辑:程序博客网 时间:2024/05/16 10:45
最近刚看完《算法》第四版的第二章,把排序算法都实现了下,总结一下这几种排序算法的优劣,改进方案和应用场景。

插入排序所需的时间取决于输入中元素的初始顺序,对一个很大且其中的元素已经有序(或者接近有序)的数组进行排序将会比对随机顺序的数组或是逆序数组进行排序快得多。

static void exchange(int[] a,int i,int j) {int temp;temp=a[i];a[i]=a[j];a[j]=temp;}public static void main(String []args){int[] a= {1,-1,0,5,4,3};for(int i=1;i<a.length-1;i++)for(int j=i;j>0&&a[j]<a[j-1];j--)exchange(a,j,j-1);for(int i=0;i<a.length-1;i++)System.out.println(a[i]+" ");}

插入排序对于部分有序的数组很有效。

大幅提高插入排序只需要在内循环中将较大的元素都像右移动而不是交换两个元素,这样访问数组的次数就能减半,改进如下:

static void exchange(int[] a, int i, int j) {int temp;temp = a[i];a[i] = a[j];a[j] = temp;}public static void main(String []args){int[] a= {1,-1,0,5,4,3};for(int i=1;i<a.length-1;i++){int temp = a[i];  int j = i;   while(j > 0 && temp<a[j-1]) {        a[j] = a[j-1];       j--; }a[j] = temp;}for(int i=0;i<a.length-1;i++)System.out.println(a[i]+" ");}


阅读全文
0 0
原创粉丝点击