【问题标题】:insertion sort algorithm using a second array C++使用第二个数组 C++ 的插入排序算法
【发布时间】:2017-07-10 08:41:06
【问题描述】:

试图理解插入排序算法..

我的算法目前是这样的:

    void insertionSort(int *array, int N) {
        int value;
        int hole;
        int *array2;


        for (int i = 1; i < N - 1; i++) {
            value = array[i]; //next item to be inserted in array 2
            hole = i;
            while (hole > 0 && array[hole - 1] > value) {
                array[hole] = array[hole - 1];
                hole = hole - 1;
            }
            array[hole] = value;
        }
    }

我的算法适用于对数组进行排序,但是我现在需要对其进行更改,以便一次构建一个新的排序数组 (array2),而不是只使用原始数组。

鉴于我已完成的算法,有没有一种简单的方法来实现这一点? 谢谢。

【问题讨论】:

  • int *array2 = new int[]; 不是有效的 C++。

标签: c++ arrays algorithm sorting insertion-sort


【解决方案1】:

您可以使用以下方法:

int *array2 = calloc(N, sizeof(int));
for(var index = 0; index < N; index++)
{
   array2[index] = array[index];
}

然后使用 array2 而不是 array 然后只需将函数的原型更改为 int *insertionSort 剩下的就是在任务结束时返回array2 但请注意内存泄漏:https://en.wikipedia.org/wiki/Memory_leak

【讨论】:

  • 什么是calloc?那个 for 循环实际上是做什么的?
  • 这是 C++,不是 SPARTAAAAAAA!使用std::vector,而不是calloc @Liam calloc 是一个用于分配和清除内存的C 函数。在 C 中使用它,虽然在 C++ 中存在有意义的边缘情况,但它们是边缘情况。使用前请慎重考虑。
  • @user4581301 不要跑题,但你什么时候会 calloc 而不是 new?
  • @Brandon 最重要的是,我想不出来。在失败的new 上不能容忍std::bad_alloc 的任何受限环境,我可能根本不会使用动态分配,或者需要用C 编写。如果我正在考虑初始化池的动态分配, std::vector 的附带好处几乎总是在高性能代码中获胜。但这并不意味着没有任何案例。
  • @Liam calloc(number_of_blocks, size_of_blocks) 占用了一部分内存,实际上(for循环)将“array”复制到“array2”中
猜你喜欢
  • 2016-08-08
  • 2018-05-03
  • 2019-04-03
  • 2014-05-11
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-11-05
  • 1970-01-01
相关资源
最近更新 更多