算法导论chapter6 堆排序的代码
按照《算法导论》上的伪代码实现了,刚开始没注意index的问题,导致错误,看来对于伪代码实现C还是要注意下啊!!
#include<iostream>
#include <time.h>
using namespace std;
const int n=11;
void print(int *a)
{
for(int i = 0; i < 11; ++i)
cout << a[i] << " ";
cout << endl;
}
void inline my_swap(int &a,int &b)
{
int temp = a;
a = b;
b = temp;
}
void max_heapify(int *a,int i,int n)
{
int l = 2*i+1,r = l + 1, largest = i;
if(l < n && a[l] > a[i])
largest = l;
if(r < n && a[r] > a[l])
largest = r;
if(largest != i)
{
my_swap(a[largest],a[i]);
max_heapify(a,largest,n);
}
}
void build_max_heap(int *a,int n)
{
for(int i = (n%2==0?n/2-1:n/2); i >= 0; --i)
max_heapify(a,i,n);
}
void heapsort(int *a,int n)
{
build_max_heap(a,n);
cout<<"建立最大堆之后: ";
print(a);
int size=n;
for(int i = n-1; i > 0; --i)
{
my_swap(a[0],a[i]);
--size;
max_heapify(a,0,size);
}
}
int main()
{
srand(time(NULL));
int *a = new int[n];
for(int i=0;i<n;++i)
a[i]=rand();
cout<<"建立最大堆之前: ";
print(a);
heapsort(a,n);
cout<<"最大堆排序之后: ";
print(a);
}