4、希尔(shell)排序
希尔排序(shell)也即是插入排序的另一种形式,只是简化了每次进行插入排序的时候,数组中的数移动的次数。
#include <bits/stdc++.h>
using namespace std;
void shell_sort(int* a, int len);
void print(int* a, int len, bool isBefore= true);
int main(){
int arr[10] = {1, 2, 66, 33, 88, 100, 18, 78, 12, 321};
print(arr, 10);
cout << "shell排序:" << endl;
shell_sort(arr, 10);
print(arr, 10, false);
return 0;
}
void shell_sort(int* a, int len){
int step = len/2;
int temp;
int j;
while(step){
for(int i = step; i < len;i++){//每个组都要做插入排序
//临时存储待插数据
temp = a[i];
j = i - step;
while(j >= 0 && a[j] > temp) {//j的范围,只有a[j]大于temp才往后覆盖
a[j + step] = a[j];
j-=step;
}
a[j+step] = temp;//temp覆盖回来
}
print(a,10);
step /= 2;
}
}
void print(int* a, int len, bool isBefore){
if(isBefore)
cout << "before sort:";
else
cout << "after sort:";
for(int i = 0; i< len; i++){
cout << a[i] << " ";
}
cout << endl;
}
下面来进行分析:
给定一个数组:1, 2, 66, 33, 88, 100, 18, 78, 12, 321
第一次的步长step = 10/2 = 5;
这个时候分成了以下五个小组,对以下五个小组分别进行插入排序,得到
【0】1 【5】100
【2】2 【6】18
【3】66 【8】78
【4】33 【9】12
【5】88 【10】321
得到序列:1 2 66 33 88 100 18 78 12 321,
接着步长step = step/2;也就是 5/2向下取整 step =2,分成以下两个小组:
【0】1 【2】66 【4】88 【6】18 【8】12
【1】2 【3】33 【5】100 【7】78 【9】321
分别对每个小组进行插入排序得到:1 2 12 33 18 78 66 100 88 321
接着step = 1;再次进行插入排序得到:1 2 12 18 33 66 78 88 100 321