#include<iostream>
#include<iomanip>
#include<stdlib.h>
#include<time.h>
using namespace std;
#define size 10
#define start 1
void Swap(int &a,int &b)
{
int buf;
buf = a;
a = b;
b = buf;
}
void Max_Heapify(int *array,int i,int heapsize)
{
int r,l,max;
l = i*2;
r = l+1;
if( l<=heapsize && array[l]>array[i] )
{
max = l;
}
else
max = i;
if( r<=heapsize && array[r]>array[max] )
{
max = r;
}
if( i != max )
{
Swap(array[i],array[max]);
Max_Heapify(array,max,heapsize);
}
}
void Build_Max_Heap(int *array)
{
int heapsize = size;
for(int i = size/2;i>0;i--)
Max_Heapify(array,i,heapsize);
}
void HeapSort(int *array)
{
int heapsize = size;
for(int i=size;i>start;i--)
{
Swap(array[start],array[heapsize]);
heapsize--;
Max_Heapify(array,start,heapsize);
}
}
int main()
{
srand(time(0));
int *array = new int[size];
int time1,time2;
cout<<"Oringinal List: ";
for(int i = start;i<=size;i++)
{
array[i] = i;
array[i] = rand()%20+1;
cout<<setiosflags(ios::right)<<setw(5)<<array[i];
}
cout<<endl<<endl;
time1 = time(0);
Build_Max_Heap(array);
HeapSort(array);
time2 = time(0);
cout<<"After List: ";
for(int j = start;j<=size;j++)
{
cout<<setiosflags(ios::right)<<setw(5)<<array[j];
}
cout<<endl<<endl;
cout<<"Time: "<<time2-time1<<" Seconds"<<endl<<endl;
return 0;
}
執行結果:
換回vista 因為雞仔老姊要看電影
只好把大螢幕電腦讓出= =