下面是堆排序的代码,其中在《编程珠玑》第14章中的代码,在建堆时候用的是从下往上的上虑,而习题2也指出了从下往上的下虑的复杂度更低,能够在O(n)复杂度内完成建堆。
#include<iostream>
#include<algorithm>
using namespace std;
void siftUp(int *A,int n)
{
int curr=n-1;
while(curr)
{
int temp=(curr-1)>>1;
if(A[temp]>A[curr])
{
swap(A[temp],A[curr]);
curr=temp;
}
else
return;
}
}
void siftDown(int *A,int n,int num)
{
int curr=num;
while(curr<=(n-2)>>1)
{
int left=2*curr+1,right=2*curr+2;
int result=left;
if(right<n && A[left]>A[right])//注意此处right的界限
result=right;
if(A[curr]>A[result])
{
swap(A[curr],A[result]);
curr=result;
}
else
return;
}
}
void buildHeap(int A[],int n)
{
for(int i=(n-2)>>1;i>=0;i--)
siftDown(A,n,i);
}
void heapSort(int *A,int n)
{
buildHeap(A,n);
for(int i=0;i<n;i++)
{
swap(A[0],A[n-1-i]);
siftDown(A,n-1-i,0);
}
}
int genRand()
{
return rand()%100;
}
int main()
{
const int N=15;
int A[N];
generate(A,A+N,genRand);
heapSort(A,N);
system("pause");
return 0;
}