Heap Sort Algorithm
Heap-Sort uses Max heap data structure to sort a sequence. The steps are:
- We need construct a max heap in place firstly, so that we can make sure that the bigest value locates on the first position of the heap.
- Swap the top value with the last value of the sequence, and shrink the size to nSize-1, and reconstruct the max heap.
- Swap loopsly and the sequence will be sorted.
The key issue is how to present a max heap data structure by an array.
- # Define left_child_index (idx) (idx * 2 + 1)
- # Define right_child_index (idx) (idx * 2 + 2)
- # Define parent_index (idx) (idx-1)/2
- /*
- Given a max-heap, if we changed a value at idx, We shoshould make sure
- That all its children are not bigger than it.
- */
- Void max_heapify (const int idx, int arr [], const int nsize)
- {
- Int ncur = idx;
- Int nleft = left_child_index (ncur );
- Int nright = right_child_index (ncur );
- If (nright <nSize-1)
- {
- If (ARR [ncur] <arr [nright])
- {
- STD: swap (ARR [ncur], arr [nright]);
- Max_heapify (nright, arr, nsize );
- }
- }
- If (nleft <nSize-1)
- {
- If (ARR [ncur] <arr [nleft])
- {
- STD: swap (ARR [ncur], arr [nleft]);
- Max_heapify (nleft, arr, nsize );
- }
- }
- }
- /*
- A Non Complete Binary Tree has (nsize + 1)/2 children
- */
- Void build_max_heap (INT arr [], const int nsize)
- {
- Int ncount = nsize-(nsize + 1)/2;
- For (INT I = 0; I <ncount; ++ I)
- {
- Max_heapify (I, arr, nsize );
- }
- }
- /*
- Build a max heap firstly, so the first one is the biggest one
- Swap with the last one, rebuild the max heap, but ignoring the last one
- */
- Void sortheap: Sort (INT arr [], const int nsize)
- {
- Alog: Print (_ T ("# Heap Sort :"));
- Alog: Print (ARR, nsize );
- Build_max_heap (ARR, nsize );
- Alog: Print (ARR, nsize );
- For (INT I = nSize-1; I> 1; -- I)
- {
- STD: swap (ARR [0], arr [I]);
- Max_heapify (0, arr, I );
- Alog: Print (ARR, nsize );
- }
- }
- Void sortheap: Test ()
- {
- Int arr [] = {2, 9, 3, 7, 8, 6, 4, 5, 0, 1 };
- Const int nsize = sizeof (ARR)/sizeof (INT );
- Sortheap: Sort (ARR, nsize );
- }
The test result:
# Heap Sort:
2 9 3 7 8 6 4 5 0 1
======================
9 8 6 7 3 4 2 5 0 1
8 7 4 6 3 2 1 5 0 9
7 6 2 4 3 1 0 5 8 9
6 5 2 4 3 1 0 7 8 9
5 4 0 3 2 1 6 7 8 9
4 3 0 1 2 5 6 7 8 9
3 2 0 1 4 5 6 7 8 9
2 1 0 3 4 5 6 7 8 9
0 1 2 3 4 5 6 7 8 9