shell排序算法

来源:互联网 发布:中国网络作家协会主席 编辑:程序博客网 时间:2024/04/29 08:17


插入排序:直接插入、shell插入

直接插入:

       从第1个数开始,把它插入到前面序列中的合适位置。

如原数列是:49,38,65,97,76,13,24,49,55,04。

第一次找到38,插入到49前面;

第二次找到65,插入后变成38,49,65

第三次找到97,······

49 38 65 97 76 13 24 49 55 4
38 49 65 97 76 13 24 49 55 4
38 49 65 97 76 13 24 49 55 4
38 49 65 97 76 13 24 49 55 4
38 49 65 76 97 13 24 49 55 4
13 38 49 65 76 97 24 49 55 4
13 24 38 49 65 76 97 49 55 4
13 24 38 49 49 65 76 97 55 4
13 24 38 49 49 55 65 76 97 4
4 13 24 38 49 49 55 65 76 97

shell插入:

用一个数组,d1,d2,···,1(例5,2,1······)

先让a[0],a[5];

a[1],a[6];

a[2],a[7];

a[3],a[8]

a[4],a[10];

有序

step0 49 38 65 97 76 13 24 49 55 4



step1 13 24 49 55 4 49 38 65 97 76
step2 4 24 13 49 38 55 49 65 97 76
step3 4 13 24 38 49 49 55 65 76 97

第二步让a[0],a[0+d2],a[0+2d2],····有序;

····

直到第k步,dk=1,这一步就是简单插入排序;

#include#includeusing namespace std;void print(int *a) { int k; for (k = 0; k < 10; k++) cout << a[k] << " "; cout << endl; }void shellinsert(int *a, int n, int d) //间隔d进行排序{for (int i = d; i < n; i++) //第d+1个数{int x = a[i];   //记录int j = i;while (j >= d&&x < a[j - d]) //如第i-d个数比较,如果大于,就不用排了直接插入;如果小于,a[j-d]后移,继续往前找,直到在合适的地方插入;{a[j] = a[j - d];j = j - d;}a[j] = x;//插入print(a);}}void shell(int* a, int n) //shell插入排序{int d = n/2;while (d>=1){shellinsert(a, n, d);print(a);d /= 2;}}void main(){int a[] = { 49,38,65,97,76,13,24,49,55,04 };print(a);shell(a, 10); //shell排序shellinsert(a, 10, 1); //d=1时的shell插入就是简单的插入排序}#include#includeusing namespace std;const int N = 10;void print(int *a) { int k; for (k = 0; k < N; k++) cout << a[k] << " "; cout << endl; }void heapadjust(int *a, int location, int length) //调整堆{int child = 2 * location + 1;while (child a[location])//如果孩子更大{int temp = a[child]; a[child] = a[location]; a[location] = temp; //交换child和location的元素}else break;//如果爸爸更大,就不用调整了location = child;  //下移child = 2 * child + 1;}}void buildheap(int *a, int length) //建立堆{int i = (length - 1) / 2;//最后一个有孩子的节点开始,调整堆for (i; i >=0; i--) //{heapadjust(a,i, length);}}void heapsort(int* a, int length) //堆排序{buildheap(a, length);//建立堆print(a);while (length>0){int temp = a[0]; a[0] = a[length - 1]; a[length - 1] = temp; //将堆顶元素删除,移动到最后heapadjust(a, 0, --length);print(a);}}void main(){int a[] = { 49,38,65,97,76,13,24,49,55,04 };print(a);heapsort(a, N);print(a);}

原创粉丝点击