C++插入排序不适用于大型数组

C++ insertion sort not working for large arrays

本文关键字:大型 数组 适用于 不适用 插入排序 C++      更新时间:2023-10-16

my insertionSort 函数适用于小数组,但不适用于具有 50,000 个随机值的数组。我花了几个小时试图弄清楚这一点,但我被难住了。这是代码:

void insertionSort(int array[], int length) {
  int swapHolder, counter, index;
  for (counter = 1; counter < length; counter++) {
        index = counter;
        while (counter > 0 && array[index - 1] > array[index]) {
              swapHolder = array[index];
              array[index] = array[index - 1];
              array[index - 1] = swapHolder;
              index--;
        }
    }
}

我的另一个排序函数(bubbleSort)适用于大型数组,但我在这个问题上挂断了。

while (counter > 0 && array[index - 1] > array[index]) {

应该是

while (index > 0 && array[index - 1] > array[index]) {

更深层次地说,插入排序的平均复杂度O(n^2),因此最适合小型数组。也就是说,它不是对 50,000 个值进行排序的正确算法。