堆排序

来源:互联网 发布:weex playground 源码 编辑:程序博客网 时间:2024/05/17 09:23
#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);}