Heap Sort - Algorithm Introduction

This section describes the Heap Sort algorithm - A complex and fast sorting algorithm that organizes original collection into a heap which is a binary tree with every node higher that its children in order, then repeatedly takes the root node to the end of the sorted section and rebuilds the heap with remaining notes.

Heap Sort is a complex and fast sorting algorithm that organizes original collection into a heap which is a binary tree with every node higher that its children in order, then repeatedly takes the root node to the end of the sorted section and rebuilds the heap with remaining notes.

The basic idea of Heap Sort algorithm can be described as these steps:

1. Organize the entire collection of data elements as a binary tree stored in an array indexed from 1 to N, where for any node at index i, its two children, if exist, will be stored at index of 2*i, and 2*i+1.

2. Divide the binary tree into two parts, the top part in which data elements are in their original order, and the bottom part in which data elements are in heap order, where each node is in higher order than its children, if any.

3. Start the bottom part with the second half of the array, which contains only leaf nodes. Of course, it is in heap order, because leaf nodes have no child.

4. Move the last node from the top part to the bottom part, compare its order with its children, and swap its location with its highest order child, if its order is lower than any child. Repeat the comparison and swapping to ensure the bottom part is in heap order again with this new node added.

5. Repeat step 4 until the top part is empty. At this time, the bottom part becomes complete heap tree.

6. Now divided the array into two sections, the left section which contains a complete heap tree, and the right section which contains sorted data elements.

7. Swap the root node with the last node of the heap tree in the left section, and move it to the right section. Since the left section with the new root node may not be a heap tree any more, we need to repeat step 4 and 5 to ensure the left section is in heap order again.

8. Repeat step 7 until the left section is empty.