自己动手写算法.Sort.HeapSort

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.

 

  1. #define LEFT_CHILD_INDEX(idx) (idx*2 + 1)
  2. #define RIGHT_CHILD_INDEX(idx) (idx*2 + 2)
  3. #define PARENT_INDEX(idx) (idx-1)/2
  4. /*
  5. Given a max-heap, if we changed a value at idx, we should make sure
  6. that all its children are not bigger than it.
  7. */
  8. void max_heapify( const int idx, int arr[], const int nSize )
  9. {
  10.     int nCur = idx;
  11.     int nLeft = LEFT_CHILD_INDEX(nCur);
  12.     int nRight = RIGHT_CHILD_INDEX(nCur);
  13.     if( nRight < nSize-1 )
  14.     {
  15.         if( arr[nCur] < arr[nRight] )
  16.         {
  17.             std::swap( arr[nCur], arr[nRight] );
  18.             max_heapify(nRight, arr, nSize);
  19.         }
  20.     }
  21.     if( nLeft < nSize-1 )
  22.     {
  23.         if( arr[nCur] < arr[nLeft] )
  24.         {
  25.             std::swap( arr[nCur], arr[nLeft] );
  26.             max_heapify(nLeft, arr, nSize);
  27.         }
  28.     }
  29. }
  30. /*
  31. a non complete binary tree has (nSize+1)/2 children
  32. */
  33. void build_max_heap(int arr[], const int nSize)
  34. {
  35.     int nCount = nSize - (nSize+1)/2;
  36.     for(int i=0; i<nCount; ++i)
  37.     {
  38.         max_heapify(i, arr, nSize);
  39.     }
  40. }
  41. /*
  42. Build a max heap firstly, so the first one is the biggest one
  43. Swap with the last one, rebuild the max heap, but ignoring the last one
  44. */
  45. void SortHeap::sort(int arr[], const int nSize)
  46. {
  47.     ALog::print(_T("# Heap Sort: "));
  48.     ALog::print(arr, nSize);
  49.     build_max_heap(arr, nSize);
  50.     ALog::print(arr, nSize);
  51.     forint i=nSize-1; i>1; --i )
  52.     {
  53.         std::swap(arr[0],arr[i]);
  54.         max_heapify(0, arr, i);
  55.         ALog::print(arr, nSize);
  56.     }
  57. }
  58. void SortHeap::test()
  59. {
  60.     int arr[] = { 2, 9, 3, 7, 8, 6, 4, 5, 0, 1};
  61.     const int nSize = sizeof(arr)/sizeof(int);
  62.     SortHeap::sort(arr, nSize);
  63. }

 

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

 

原文地址:https://www.cnblogs.com/aiwz/p/6333130.html