I need to follow my heart.

Apr 15, 2009

HEAP-SORT

Input: A[]

Main Algorithm:
HEAP-SORt(A)
{
BUILD-MAX-HEAP(A);
for (int i = length[A]; i >=1; i--)
{
exchange(A[1], A[i]);
heap-size[A]--;
MAX-HEAPIFY(A, 1);
}
}

Subroutines:
BUILD-MAX-HEAP(A)
{
heap-size[A] = length[A];
for (int i = [heap-size[A]/2]; i >= 0; i--)
MAX-HEAPIFY(A, i);
}

MAX-HEAPIFY(A, i)
{
l = 2i;
r = 2i +1;
if (l <= heap-size[A] && A[l] > A[i])
largest = l;
else
largest = i;
if (r <= heap-size[A] && A[r] > A[largest])
largest = r;
if (largest != r)
{
exchange(A[i], A[largest]);
MAX-HEAPIFY(A, largest);
}
}

No comments: