当我使用大于10的数组时,为什么堆排序不起作用? c#

时间:2019-03-09 19:25:46

标签: heapsort

代码:

class Program
{
    static void HeapSort(int[] array, int n) 
    {
        for (int i = n / 2 - 1; i >= 0; i--) 
            Heapify(array, n, i);
        for (int i = n - 1; i >= 0; i--)       
        {
            int temp = array[0];
            array[0] = array[i];
            array[i] = temp;
            Heapify(array, i, 0);
        }
    }
    static void Heapify(int[] array, int n, int i)
    {
        int largest = i;                                   // largest = 4
        int left = 2 * i + 1;                              // left = 9 
        int right = 2 * i + 2;                             // right = 10
        if (left < n && array[left] > array[largest])      //ar left < 10 ir ar ar9 > ar4
            largest = left;                                //left tampa 
        if (right < n && array[right] > array[largest])
            largest = right;
        if (largest != i)
        {
            int swap = array[i];
            array[i] = array[largest];
            array[largest] = swap;
            Heapify(array, n, largest);
        }
    }
    public static void Main()
    {
        int[] arr = { 55, 25, 89, 34, 12, 19, 78, 95, 1, 100, 99, 98};
        int n = 12, i;
        Console.WriteLine("Heap Sort");
        Console.Write("Initial array is: ");
        for (i = 0; i < n; i++)
        {
            Console.Write(arr[i] + " ");
        }
        HeapSort(arr, 10);
        Console.Write("\nSorted Array is: ");
        for (i = 0; i < n; i++)
        {
            Console.Write(arr[i] + " ");
        }
        Console.ReadLine();
    }
}

当我使用10的数组时,效果很好,但是如果添加元素,则将它们放在数组的末尾。示例:

int[] arr = { 55, 25, 89, 34, 12, 19, 78, 95, 1, 100};
        int n = 10, i;

输出: 堆排序 初始数组是:55 25 89 34 12 19 78 95 1100 排序数组为:1 12 19 25 34 55 78 89 95 100

现在,如果我再添加几个:

int[] arr = { 55, 25, 89, 34, 12, 19, 78, 95, 1, 100, 99, 98, 120, 44};
        int n = 14, i;

输出: 堆排序 初始数组是:55 25 89 34 12 19 78 95 1 100 99 98 120 44 排序的数组是:1 12 19 25 34 55 78 89 95 100 99 98 120 44

为什么不对其余部分排序?

1 个答案:

答案 0 :(得分:0)

我发现了错误。我忘记在Main函数的第一个HeapSort调用中更改10,而在此处保留10而不是n。将其更改为n可解决该问题。