Apr 19, 2011

sort an array using heapsort

void max_heapify(int* u, int i, int size)
{
//push down the ith element in the max tree
int l = 2*i+1;
int r = 2*i+2;
int largest =i;
if(l<=size && u[l]>u[largest])
largest = l;
else
largest = i;
if(r<=size && u[r]>u[largest])
largest = r;
if(i != largest)
{
//exchange i and largest and call recurse max_heapify
int t=u[i];
u[i] = u[largest];
u[largest] = t;
max_heapify(u, largest, size);
}
}

void build_max_heap(int* u, int size)
{
for(int i=size/2; i>=0; i--)
{
max_heapify(u, i, size);
}
}

void heap_sort(int* u, int size)
{
build_max_heap(u, size);

cout << "max heap: ";
print_arr(size);

int hsize = size;
for(int i=0; i< size; i++)
{
hsize--;
int t= u[0];
u[0] = u[hsize];
u[hsize] = t;
max_heapify(u, 0, hsize-1);
}
}

No comments: