Tuesday 19 July 2011

Heap Sort.

Forming the Heap:

  1. Start at the root node of the tree.
  2. If the root is larger than its children, stop- you have a heap.
  3. If not, exchange the root with the largest child
  4. Consider the child as the current root and repeat the step from 1.
Sorting Algorithm:

  1. Repeat n-1 times.
  2. Exchange the root value with the last value in the tree.
  3. Now, Drop the last value form the tree.
  4. Reform the heap.
Example:
Consider the array elements that are already arranged as heap. Let the array elements be 87,57,44,12,15,19,23. Here's the Heap.

Exchange the root with the last value.

Drop the last value in the heap.
Reform the heap. Find the largest child of the current root.
Exchange the values.
Now exchange the root of the heap with the last value.
Drop the last value in the heap.
Reform the heap. Find the largest child of the current root.

Exchange the values.

Now exchange the root of the heap with the last value.
                                     
Drop the last value in the heap.


Reform the heap. Find the largest child of the current root.

Exchange the values.

Now exchange the root of the heap with the last value.

Drop the last value in the heap.

Reform the heap. Find the largest child of the current root.

Exchange the values.

Now exchange the root of the heap with the last value.


Drop the last value in the heap.
Reform the heap. Find the largest child of the current root.

Exchange the values

Now exchange the root of the heap with the last value.

Drop the last value in the heap.
The heap consists of a single value at this point  which is in its proper position.
So the List is sorted.


No comments:

Post a Comment