T(n) = nlgn
/**
* @brief Heap Sort
* @author An
* @data 2013.5.15
**/
#include <iostream>
using namespace std;
void MaxHeapify ( int *array, int index, int heapSize )
{
int largest = index;
int leftNode = 2 * index + 1; //index is from 0 to heapSize-1
int rightNode = 2 * index + 2;
if ( leftNode < heapSize && array[leftNode] > array[largest] )
largest = leftNode;
if ( rightNode < heapSize && array[rightNode] > array[largest] )
largest = rightNode;
if ( largest != index )
{
int temp = array[index];
array[index] = array[largest];
array[largest] = temp;
MaxHeapify( array, largest, heapSize );
}
}
void BuildMaxHeap ( int *array, int heapSize )
{
for ( int i = heapSize / 2 - 1; i >= 0; --i )
{
MaxHeapify( array, i, heapSize );
for ( int j = 0; j < heapSize; ++j )
cout << array[j] << " ";
cout << endl;
}
}
void HeapDelete( int *array, int index, int heapSize )
{
int temp = array[index];
array[index] = array[heapSize - 1];
array[heapSize - 1] = temp;
--heapSize;
int parent = ( index - 1 ) / 2;
if ( array[index] <= array[parent] )
{
MaxHeapify( array, index, heapSize );
}
else
{
while ( index > 0 && array[index] > array[parent] )
{
int tmp = array[parent];
array[parent] = array[index];
array[index] = tmp;
index = parent;
parent = ( index - 1 ) / 2;
}
}
}
void HeapSort ( int *array, int length )
{
BuildMaxHeap( array, length );
int heapSize = length;
for ( int i = length - 1; i > 0; --i )
{
int temp = array[i];
array[i] = array[0];
array[0] = temp;
--heapSize;
MaxHeapify( array, 0, heapSize );
for ( int i = 0; i < heapSize; ++i )
cout << array[i] << " ";
cout << endl;
}
}
//print array
void printArray( int *array, int length )
{
for ( int i = 0; i < length; ++i )
{
cout << array[i] << " ";
}
cout << endl;
}