前幾天,看到一篇前輩的博文“程式員必知的8大排序”,不禁的手癢起來,重新翻開嚴蔚敏老師的《資料結構》複習了一遍,然後一一的用java去實現,其中有不足之處,還望各位道友指正出來。
先來看看8種排序之間的關係:
1,
直接插入排序
(1)基本思想:在要排序的一組數中,假設前面(n-1) [n>=2] 個數已經是排
好順序的,現在要把第n個數插到前面的有序數中,使得這n個數
也是排好順序的。如此反覆迴圈,直到全部排好順序。
(2)執行個體
(3)用java實現
package com.njue; publicclass insertSort {public insertSort(){ int a[]={49,38,65,97,76,13,27,49,78,34,12,64,5,4,62,99,98,54,56,17,18,23,34,15,35,25,53,51}; int temp=0; for(int i=1;i<a.length;i++){ int j=i-1; temp=a[i]; for(;j>=0&&temp<a[j];j--){ a[j+1]=a[j]; //將大於temp的值整體後移一個單位 } a[j+1]=temp; } for(int i=0;i<a.length;i++) System.out.println(a[i]);}}
2,
希爾排序(最小增量排序)
(1)基本思想:演算法先將要排序的一組數按某個增量d(n/2,n為要排序數的個數)分成若干組,每組中記錄的下標相差d.對每組中全部元素進行直接插入排序,然後再用一個較小的增量(d/2)對它進行分組,在每組中再進行直接插入排序。當增量減到1時,進行直接插入排序後,排序完成。
(2)執行個體:
(3)用java實現
publicclass shellSort {publicshellSort(){ int a[]={1,54,6,3,78,34,12,45,56,100}; double d1=a.length; int temp=0; while(true){ d1= Math.ceil(d1/2); int d=(int) d1; for(int x=0;x<d;x++){ for(int i=x+d;i<a.length;i+=d){ int j=i-d; temp=a[i]; for(;j>=0&&temp<a[j];j-=d){ a[j+d]=a[j]; } a[j+d]=temp; } } if(d==1) break; } for(int i=0;i<a.length;i++) System.out.println(a[i]);}}
接下一篇:程式員必知的8大排序(二)-------簡單選擇排序,堆排序(java實現) .