希爾排序(最小增量排序)
時間複雜度:O(n*log2(n))~O(n2),平均時間複雜度大致是O(n√n)
空間複雜度:O(1)
不穩定
核心代碼:
/**
* 希爾排序(最小增量排序)
* @author jin
*/
public class ShellSort {
public void sort(){
int[] a={2,3,5,4,6,1,7,0,9,8,11,10};
double d1=a.length;
int tmp=0;
while(true){
d1=Math.ceil(d1/2);//Math.ceil爲向上取整,.round爲四捨五入,.floor爲向下取整
int d=(int) d1;
for(int x=0;x<d;x++){ //從0到d,遍歷一遍
for(int i=x+d;i<a.length;i+=d){ //對每一組的元素進行插入排序
int j=i-d;
tmp=a[i];
for(;j>=0&&tmp<a[j];j-=d){
a[j+d]=a[j];
}
a[j+d]=tmp;
}
}
if(d==1){
break; //如果d==1,跳出while循環
}
}
for(int i=0;i<a.length;i++){
System.out.println(a[i]);
}
}
}
希爾排序是一組數,按某個增量d1(n/2)分爲若干組,每組數進行直接插入排序;再用一個增量d2(n/2)分爲若干組,每組數進行直接插入排序;當增量減爲1時,進行直接插入排序,完成。
用到的知識點:
Math.ceil()爲向上取整,
Math.floor()爲向下取整,
Math.round()爲四捨五入。
例:
Math.ceil(4.3)=5.0;
Math.floor(4.3)=4.0;
Math.round(4.3)=4.0;
(1)先對數組對半分,如果爲奇數,則向上取整;
(2)然後通過直接插入排序對其進行排序;
(3)然後再返回來,執行步驟(1);
(4)當增量爲1時,就跳出循環。
插入排序時,以d爲一個週期,而不是以前的1爲一個週期,即(2,3,6,5)這四個數,2和6爲一組,進行插入排序;3和5爲一組,進行插入排序,然後再四個數爲一組,進行插入排序……