哈希排序:
改進了得插入排序,將待排序的數組根據差量分成若干的的子數組,分別進行插入排序,最后一步當差量為1的時候也就是直接的插入排序了,只是這時數組的序列已經大概是有序的了。 關鍵是增量
代碼如下:
//希爾排序 void shell(int unsort[],int dx, int lenght) { for(int i = 0; i < dx; i++) { //插入排序 for(int j = 1; i+j*dx < lenght; j++) { if(unsort[i+j*dx] < unsort[i+(j-1)*dx]) { int k = j; int flag = unsort[i+j*dx]; while(i+(k-1)*dx > 0 && flag < unsort[i+(k-1)*dx]) { unsort[i+k*dx] = unsort[i+(k-1)*dx]; k--; } unsort[i+k*dx] = flag; } } } } //這里增量的取值規則為上次增量的一半,第一次為lenght/2 void shell_sort(int unsort[], int lenght) { int len = lenght; int dx = lenght/2; int i = 1; while(dx >= 1) { shell(unsort, dx, lenght); dx = dx/2; cout<<"第"<<i<<"趟:"; for(int k = 0; k < lenght; k++) { cout<<unsort[k]<<" "; } cout<<endl; i++; } }
結果如下:
注意:
這個排序的方法增量的選取決定了排序的效率,一般選的是(n/2,n/4,n/8...)n為數組的長度,每次選取為上次差量值得一半
詳細步驟: