// choice sort
#include<iostream>
#include<Windows.h>
#include<ctime>
using namespace std;
// use 1000,00 to test
int const size = 1000000;
// template function declare
template<class T>
void Heap_sort(T *data,const int length);
// template function
template<class T>
void Make_heap(T *data,const int length);
// template function
template<class T>
void Heap_downcast(T *data,int i,const int length);
int main()
{
DWORD S,E;
int * data = new int[size];
for(int i =0 ; i<size; i++)
{
data[i] = rand();
}
cout<<"data initialize over"<<endl;
S = GetTickCount();
Heap_sort(data,size);
E = GetTickCount();
//for(int i =0 ; i<size; i++)
//{
// cout<<data[i]<<endl;
//}
cout<<endl<<"給"<<size<<"個數據選擇排序,費時"<<E-S<<"毫秒"<<endl;
system("pause");
return 0;
}
// template function
template<class T>
void Heap_sort(T *data,const int length)
{
if(data != NULL && length >= 0)
{
Make_heap(data,length);
T d;
int L = length;
while(L>1)
{
d=data[L-1];
data[L-1] = data[0];
data[0] =d;
L--;
Heap_downcast(data,0,L);
}
cout<<endl;
}
else
{
cout<<"exception of input choice sort"<<endl;
}
}
// template function
template<class T>
void Make_heap(T *data,const int length)
{
if(data != NULL && length >= 0)
{
for(int i=length/2-1;i>=0;i--)
{
Heap_downcast(data,i,length);
}
}
else
{
cout<<"exception of input make heap"<<endl;
}
}
// template function
template<class T>
void Heap_downcast(T *data,int i,const int length)
{
if(data != NULL && length >= 0)
{
T max ;
// have two children
while(i*2+2 <length)
{
max = data[i];
if(max >= data[i*2+1] && max >= data[2*i+2])
break;
// right child bigger
if( data[i*2+2]>data[2*i+1] && data[i*2+2]>max)
{
max = data[i*2+2];
data[i*2+2] = data[i];
data[i] = max;
i = i*2+2;
}
// left child bigger
else if( data[i*2+1] >= data[2*i+2] && data[i*2+1]>max )
{
max = data[i*2+1];
data[i*2+1] = data[i];
data[i] = max;
i = i*2+1;
}
}
// have one child
if(i*2+1 < length)
{
if(data[i*2+1]>data[i])
{
max = data[i*2+1];
data[i*2+1] = data[i];
data[i] = max;
}
}
}
else
{
cout<<"exception of input Heap_downcast"<<endl;
}
}