<h1>原理参考:http://blog.csdn.net/morewindows/article/details/6709644</h1>
/**********************************************************/
//堆插入
void MinHeapfixup(int a[],int n,int num){
a[n] = num;
int j,temp;
temp = num;
j = (n-1)/2;
while (j >= 0 && n != 0)
{
if(temp >= a[j])
break;
a[n] = a[j];
n = j;
j = (n-1)/2;
}
a[i] = temp;
}
//堆删除
void MinHeapfixdown(int a[],int i,int n){
int j,temp;
temp = a[i];
j = 2*i + 1;
while (j < n)
{
if(j+1 < n && a[j+1] < a[j])
++j;
if(temp <= a[j])
break;
a[i] = a[j];
i = j;
j = 2*i +1;
}
a[i] = temp;
}
void HeapDelete(int a[],int n){
swap(a[0],a[n-1]);
MinHeapfixdown(a,0,n-1);
}
//数组堆化
void MakeHeap(int a[],int n){
for (int i = n/2-1; i>=0; --i)
{
MinHeapfixdown(a,i,n);
}
}
//堆排序
void HeapSort(int a[],int n){
for (int i=n-1; i>=1; --i)
{
swap(a[0],a[i]);
MinHeapfixdown(a,0,i);
}
}
int _tmain(int argc, _TCHAR* argv[])
{
int a[] = {9,12,17,30,50,20,60,65,4,19};
int i = 0;
cout<<"原数组"<<endl;
while (i<10)
{
cout<<a[i]<<" ";
++i;
}
cout<<endl;
MakeHeap(a,10);
i = 0;
cout<<"数组堆化"<<endl;
while (i<10)
{
cout<<a[i]<<" ";
++i;
}
cout<<endl;
HeapSort(a,10);
i = 0;
cout<<"堆化后排序"<<endl;
while (i<10)
{
cout<<a[i]<<" ";
++i;
}
system("pause");
return 0;
}