Sunday, May 01, 2016

Heap sort implementation in C#

Here's a heap sort implementation in C#:

  1. class HeapSort  
  2. {  
  3.     public void Sort(int[] a)  
  4.     {  
  5.         // Turn the array into a max heap  
  6.         for (int i = (a.Length / 2) - 1; i >= 0; i--)  
  7.         {  
  8.             MaxHeapify(a, i, a.Length);  
  9.         }  
  10.   
  11.         // Remove the largest element from the max heap and put it on the end,  
  12.         // and then max heapify the heap which is now 1 smaller  
  13.         for (int i = a.Length - 1; i >= 1; i--)  
  14.         {  
  15.             Swap(a, 0, i);  
  16.             MaxHeapify(a, 0, i);  
  17.         }  
  18.     }  
  19.   
  20.     private void MaxHeapify(int[] a, int i, int n)  
  21.     {  
  22.         int idxLeft  = (i + 1) * 2 - 1;  
  23.         int idxRight = (i + 1) * 2 - 1 + 1;  
  24.   
  25.         int largest = i;  
  26.   
  27.         if (idxLeft < n && a[idxLeft] > a[largest])  
  28.         {  
  29.             largest = idxLeft;  
  30.         }  
  31.   
  32.         if (idxRight < n && a[idxRight] > a[largest])  
  33.         {  
  34.             largest = idxRight;  
  35.         }  
  36.   
  37.         if (largest != i)  
  38.         {  
  39.             Swap(a, i, largest);  
  40.             MaxHeapify(a, largest, n);  
  41.         }  
  42.     }  
  43.   
  44.     private void Swap(int[] a, int i, int j)  
  45.     {  
  46.         int tmp = a[i];  
  47.         a[i] = a[j];  
  48.         a[j] = tmp;  
  49.     }  
  50. }