之前看其他算法和数据结构书的时候觉得堆排序的代码比较难写,今天看过《算法导论》发现也不是那么难,所以就动手自己写了一个。原理就是根据算法导论第三版堆排序伪代码而来的。
#include<iostream>
using namespace std;
const int ARRAY_SIZE=10;
int a[ARRAY_SIZE]={4,1,3,2,16,9,10,14,8,7};
//调整pos位置,使得pos和其直接左右孩子满足大堆条件
void max_heapify(int a[],int pos,int heap_size)
{
int l=2*pos+1,r=2*pos+2;//因为下标从0开始,所以这里l和r都多加了1
int largest;
if(l<=heap_size&&a[l]>a[pos])
largest=l;
else
largest=pos;
if(r<=heap_size&&a[r]>a[largest])
largest=r;
if(largest!=pos)
{
int tmp=a[pos];
a[pos]=a[largest];
a[largest]=tmp;
max_heapify(a,largest,heap_size);//改变了largest位置的值,则以largest为根的子树也要调整
}
}
//建堆过程
void build_max_heap(int a[],int n)
{
for(int i=n/2-1;i>=0;i--)//注意数组下标从0开始,所以这里n/2-1
{
max_heapify(a,i,n-1);//heap_size=n-1
}
}
int main()
{
build_max_heap(a,ARRAY_SIZE);
for(int