C++堆排序

来源:互联网 发布:广数英制螺纹怎么编程 编辑:程序博客网 时间:2024/06/03 17:01
/**用自底向上算法,从给定的数组元素中构造一个堆*输入:一个可排序元素的数组H[1...n]*输出:一个堆H[1...n]*/int HeapBottom(int H[],int n){int j,k,v;bool heap;for (int i = n/2; i >0; i--){k=i;v=H[k];heap=false;while (!heap&&2*k<=n){j=2*k;if (j<n)if (H[j]<H[j+1])j=j+1;if(v>=H[j])heap=true;else{H[k]=H[j];k=j;}}H[k]=v;}return 0;}/**第一步:根的键和堆的最后一个键K交换*第二步:堆的规模减一*第三步:按照上面自底向上堆构造的算法中的做法,把K沿着树向下筛选,对这颗较小的树进行堆化*/int HeapSort(int H[],int n){while (n>1){int temp;temp=H[1];H[1]=H[n];H[n]=temp;n--;HeapBottom(H,n);}return 0;}
#include<iostream>#include"HeapSort.h"using namespace std;int main(){int array[7] = {0,2,9,7,6,5,8}; //注:堆从H[1]开始,到H[n]int n=sizeof(array)/sizeof(int);cout<<"排序前:";for (int i = 1; i < n; i++)cout<<array[i]<<" ";cout<<endl;HeapBottom(array,n);cout<<"排序后:";for (int i = 1; i < n; i++)cout<<array[i]<<" ";cout<<endl;    return 0;  }