标签:
#include <iostream> using namespace std; void CreatHeap(int a[],int n,int h) { int i,j,flag; int temp; i = h; j = 2*i + 1; temp = a[i]; flag = 0; while(j < n && flag != 1) { if(j < n-1 && a[j] < a[j+1])j++; if(temp > a[j]) flag = 1; else { a[i] = a[j]; i = j; j = 2*i + 1; } } a[i] = temp; } void InitCreatHeap(int a[],int n) { int i; for(i = (n-2)/2;i >= 0;i--) CreatHeap(a,n,i); } void HeapSort(int a[],int n) { int i; int temp; InitCreatHeap(a,n); for(i = n-1;i >0;i--) { temp = a[0]; a[0] = a[i]; a[i] = temp; CreatHeap(a,i,0); } } int main() { int a[8] = {10,50,32,5,76,9,40,88}; HeapSort(a,8); for(int i = 0;i < 8;i++) cout<<a[i]<<endl; return 0; }
首先把有n个元素的数组a初始化为最大堆,然后循环执行至数组为空,①把数组第一个元素和最后一个元素调换②最大元素个数减一③调整根节点为最大堆
标签:
原文地址:http://www.cnblogs.com/dynas/p/4935401.html