堆可以分为最大堆和最小堆。其中基于最大堆的堆排序如下:
/*****************************
houyong
*****************************/
#include <iostream>
using namespace std;
void exchange (int &a, int &b)
{
int temp = a;
a = b;
b = temp;
}
/** 创建最大堆
*
* @param A为待创建数组
* @param n为数组大小
* @param i为起始位置
*
*/
void MAX_HEAP_Adjust(int A[], int n, int i)
{
int left = 2*i + 1;
int right = 2*i + 2;
int largest = i;
while(left<n || right<n)
{
if(left<n&&A[left]>A[i])
{
largest = left;
}
if(right<n&&A[right]>A[largest])
{
largest = right;
}
if(largest!=i)
{
exchange(A[largest], A[i]);
i = largest;
left = 2*i + 1;
right = 2*i + 2;
}
else
{
break;
}
}
}
void MAX_HEAP_Build(int A[], int n)
{
int i;
int beginpoint = n/2 -1; //最后一个非叶子结点
for(i = beginpoint; i>=0; i--)
{
MAX_HEAP_Adjust(A, n, i);
}
}
/**
*对最大堆排序,因为A[0]是最大,所以每次将最后一个放到A[0]处,长度减一,再重新调整堆成为最大堆
*
*/
void MAX_HEAP_Sort(int A[], int n)
{
int currentLength = n;
while(currentLength>0)
{
exchange(A[0], A[currentLength-1]); //交换
currentLength = currentLength - 1; //长度减一
MAX_HEAP_Adjust(A, currentLength, 0); //调整
}
}
int main()
{
int A[] = {4, 1, 3, 2, 16, 9, 10, 14, 8, 7};
cout<<"A: ";
for(int i=0; i<10; i++)
cout<<A[i]<<" ";
cout<<endl;
MAX_HEAP_Build(A, 10);
cout<<"MAX_HEAP_Build A: ";
for(int i=0; i<10; i++)
cout<<A[i]<<" ";
cout<<endl;
MAX_HEAP_Sort(A, 10);
cout<<"MAX_HEAP_Sort A: ";
for(int i=0; i<10; i++)
cout<<A[i]<<" ";
cout<<endl;
return 0;
}
/**
A: 4 1 3 2 16 9 10 14 8 7
MAX_HEAP_Build A: 16 14 10 8 7 9 3 2 4 1
MAX_HEAP_Sort A: 1 2 3 4 7 8 9 10 14 16
*/