title: Heap Sort in C# sorting with large sized arrays
body: <p>I have a small problem with my heap sort implementation. Basically, I implemented it, and it essentially works with arrays that have 6 or less elements. But for some reason, anything larger than 6 elements, and the sorting is buggy.</p>
  
  <p>For example:</p>
  
  <p>Sorting {10,64,7,99,32,18} gives this: 7,10,18,32,64,99</p>
  
  <p>Sorting {10,64,7,99,32,18,2,48} gives this: 2,7,10,32,<strong><em>18</em></strong>,48,64,99</p>
  
  <p>My implementation below. As the size of the array gets larger, the sorting becomes more scrambled in a sense and gives an incorrect output. How can I fix this?</p>
  
  <pre><code>class Program
  {
      static void Main(string[] args)
      {
          int[] arr = { 10, 64, 7, 99, 32, 18};
          HeapSort hs = new HeapSort();
          hs.PerformHeapSort(arr);
          Console.ReadLine();
      }
  }
  class HeapSort
  {
      private int heapSize;
  
      private void BuildHeap(int[] arr)
      {
          heapSize = arr.Length-1;
          for (int i = heapSize/2; i &gt;= 0; i--)
          {
              Heapify(arr, i);
          }
      }
  
      private void Swap(int[] arr, int x, int y)//function to swap elements
      {
          int temp = arr[x];
          arr[x] = arr[y];
          arr[y] = temp;
      }
      private void Heapify(int[] arr, int index)
      {
          int left = 2 * index;
          int right = 2 * index + 1;
          int largest;
  
          if (left &lt;= heapSize &amp;&amp; arr[left] &gt; arr[index])
          {
              largest = left;
          }
          else
          {
              largest = index;
          }
          if (right &lt;= heapSize &amp;&amp; arr[right] &gt; arr[largest])
          {
              largest = right;
          }
          else
          {
              largest = index;
          }
  
          if (largest != index)
          {
              Swap(arr, index, largest);
              Heapify(arr, largest);
          }
      }
      public void PerformHeapSort(int[] arr)
      {
          BuildHeap(arr);
          for (int i = arr.Length-1; i &gt;= 0; i--)
          {
              Swap(arr, 0, i);
              heapSize--;
              Heapify(arr, 0);
          }
          DisplayArray(arr);
      }
      private void DisplayArray(int[] arr)
      {
          for (int i = 0; i &lt; arr.Length; i++)
          { Console.Write("[{0}]", arr[i]); }
      }
  }
  </code></pre>