Heap Sort in C# sorting with large sized arrays

Karim O. picture Karim O. · Nov 25, 2014 · Viewed 10.6k times · Source

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.

For example:

Sorting {10,64,7,99,32,18} gives this: 7,10,18,32,64,99

Sorting {10,64,7,99,32,18,2,48} gives this: 2,7,10,32,18,48,64,99

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?

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 >= 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 <= heapSize && arr[left] > arr[index])
        {
            largest = left;
        }
        else
        {
            largest = index;
        }
        if (right <= heapSize && arr[right] > 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 >= 0; i--)
        {
            Swap(arr, 0, i);
            heapSize--;
            Heapify(arr, 0);
        }
        DisplayArray(arr);
    }
    private void DisplayArray(int[] arr)
    {
        for (int i = 0; i < arr.Length; i++)
        { Console.Write("[{0}]", arr[i]); }
    }
}

Answer

Evgeniy Mironov picture Evgeniy Mironov · Nov 25, 2014

Errors contains in function Heapify. The corrected version of the function:

        private void Heapify(int[] arr, int index)
        {
            int left = 2 * index + 1;
            int right = 2 * index + 2;
            int largest = index;
            if (left <= heapSize && arr[left] > arr[index])
            {
                largest = left;
            }

            if (right <= heapSize && arr[right] > arr[largest])
            {
                largest = right;
            }

            if (largest != index)
            {
                Swap(arr, index, largest);
                Heapify(arr, largest);
            }
        }