c++ - 通过将最小的数字放在第一位来将两个数组组合成一个

标签 c++ function sorting

我需要遍历 a 和 b 数组,将元素从 a 和 b 复制到 combo 中,这样 combo 最终会被排序。

例如,如果 a 是 {3, 5, 7, 7, 9} 并且 b 是 {2, 5, 8, 1234}(所以 combo 必须有 9 个元素),那么这个函数会将 combo 设置为 {2 , 3, 5, 5, 7, 7, 8, 9, 1234}。我需要有效地做到这一点:当我将值放入组合时,我需要将它们放在正确的位置;不要随意,稍后重新排列它们。

我在 while 循环中尝试了一个嵌套的 for 循环,但我得到了一些奇怪的结果。我似乎无法想出一种方法来超越最低数字。例如,一旦我将最小的数字添加到组合数组中,我就无法弄清楚如何丢弃它本身。谢谢您的帮助。

void merge( 
    unsigned combo[], 
    const unsigned a[],
    unsigned aElements,
    const unsigned b[],
    unsigned bElements 
){

    if (mySort(a, aElements) == 0) {
        cout << "The first array is not sorted";
        exit(1);
    }

    if (mySort(b, bElements) == 0) {
        cout << "The second array is not sorted";
        exit(1);
    }

    unsigned combinedElements;
    unsigned lowest = 0;
    unsigned i = 0;

    combinedElements = aElements + bElements;

    while (i < combinedElements) {
        for (int n = 0; n < combinedElements; n++) {
            if (a[i] < b[n]) {
                lowest = a[i];
            }

            else {
                lowest = b[n];
            }
        }

        combo[i] = lowest;
        i++;
        cout << combo[i] << endl;
    }


}

最佳答案

除非这是家庭作业,否则请使用 std::merge

void merge( 
    unsigned combo[], 
    const unsigned a[],
    unsigned aElements,
    const unsigned b[],
    unsigned bElements 
){
    std::merge(a, a+aElements, b, b+bElemnts, combo);
}

如果这家庭作业,试试这个算法:

index_result = 0; index_a = 0; index_b = 0;
while(index_a < size_a && index_b < size_b)
  if(a[index_a] < b[index_b])
    result[index_result++] = a[index_a++]
  else
    result[index_result++] = b[index_b++]
while(index_a < size_a)
  result[index_result++] = a[index_a++]
whle(index_b < size_b)
  result[index_result++] = b[index_b++]

关于c++ - 通过将最小的数字放在第一位来将两个数组组合成一个,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14885867/

相关文章:

c++ - 更高级地使用 ceil() 函数

c++ - 使用模板区分类型

function - 不导入模块不区分大小写。我需要原始输出而不是较低的输出

c++ - 用 C++ 编写程序,我需要帮助

javascript - 创建 JavaScript 函数来更改先前声明的变量

java - 尝试对按各自顺序给定的字符串进行排序,无法使用集合

PHP + MySQL - 排序查询

c++ - 编写一个使多个容器看起来像一个的迭代器

c# - Cosmos DB 分页和排序

c++ - 有符号整数溢出在 C++ 中仍然是未定义的行为吗?