Friday, November 14, 2014

Heap #3: HeapSort Ascending Order


#include<cstdio>
#include<iostream>
using namespace std;

int Parent(int index)
{
return index>>1; // index/2
}

int LeftChild(int index)
{
return index<<1; // 2 * index
}

int RightChild(int index)
{
return (index<<1) + 1; // (2 * index) + 1
}

void Max_Heapify(int *x, int index, int heapsize)
{
//cout<<"Visit-->"<<index<<endl;
int left = LeftChild(index);
int right = RightChild(index);
int largest = index;

if(left<=heapsize && x[left]>x[largest])
{
largest = left;
}

if(right<=heapsize && x[right]>x[largest])
{
largest = right;
}

if(largest != index)
{
swap(x[largest], x[index]);
Max_Heapify(x, largest, heapsize);
}
}

void Build_Max_Heap(int *x, int heapsize)
{
for(int I=(heapsize/2); I>0; I--)
{
Max_Heapify(x, I, heapsize);
}
}

void HeapSort(int *x, int heapsize)
{
Build_Max_Heap(x, heapsize);

for(int I = heapsize; I>1; I-- )
{
swap(x[1], x[I]);
heapsize--;
Max_Heapify(x, 1, heapsize);
}
}


void printArray(int *x, int arraySize)
{
for(int I=0; I<arraySize; I++)
{
cout<<I<<" "<<x[I]<<endl;
}

cout<<endl;
}


int main()
{
//Heap start from index 1
int a[] = {-1,2,3,9,5,6,7,8};

int arraySize = sizeof(a)/sizeof(*a);

printArray(a, arraySize);

//For Ascending order
HeapSort(a, arraySize-1);

printArray(a, arraySize);


return 0;
}


No comments:

Post a Comment