堆排序(源码)

源码:

//HeapSort.cpp

#include <iostream>
using namespace std;


//about heap:
//the last leaf node is a[n-1]
//the last non-leaf node is a[n/2-1];
// a[i]
// / \
// a[2i+1] a[2i+2]

//i: current node
//n: length of heap
int MaxHeapify(int a[],int i, int n)
{
int l = 2*i+1;
int r = 2*i+2;
int largest = i;
if (l<n && a[l]>a[i])
{
largest = l;
}
if (r<n && a[r]>a[largest])
{
largest = r;
}
if (largest != i)
{
int temp = a[i];
a[i] = a[largest];
a[largest] =temp;
MaxHeapify(a,largest,n);
}
return 0;
}
int BuildMaxHeap(int a[], int n)
{
//from the last non-leaf node.
for (int i=n/2-1; i>=0;i--)
{
MaxHeapify(a,i,n);
}
return 0;
}
void swap(int* i, int* j)
{
int tmp = *i;
*i = *j;
*j = tmp;
}
int Heapsort(int a[],int n)
{
BuildMaxHeap(a,n);
cout<<"After build max heap."<<endl;
for (int i=0;i<n;i++)
{
cout<<a[i]<<" ";
}
cout<<endl;
//output heap element
//from the root node.
for (int j=n-1;j>0;j--)
{
swap(&a[0],&a[j]); //a[j] is largest
MaxHeapify(a,0,j);
}
cout<<"After heap sort"<<endl;
for (int k=0; k<n;k++)
{
cout<<a[k]<<" ";
}
cout<<endl;

return 0;
}
int main()
{
int a[] ={6,3,8,9,7,20,12,7,5,3,2};
Heapsort(a,sizeof(a)/sizeof(a[0]));
system("pause");
return 0;
}

posted on 2014-05-19 01:38  Acor  阅读(497)  评论(0编辑  收藏  举报

导航