c++ - 合并排序不正确的输出

标签 c++ sorting

我正在尝试使用以下合并排序函数对数组进行排序。但是它没有给我预期的输出。 它不会打印出正确/预期的输出,即

输入:5,4,3,2,1
输出:1,2,3,4,5

相反,它给出:2,3,4,5,1,9,8,7,8,4,1,8,8,2。

#include <iostream>
#include <cmath>
#include <ctime>
#include <cstdlib>

using namespace std;

void mergeSort(int a[], int low , int high,int res[]);
void merge(int a[], int low , int mid , int high,int res[]);
void mergeSort(int numbers[], int temp[], int array_size);

const int SIZE=5;

int main () {

    int sorted[SIZE];
    for (int i=0; i<SIZE; i++) {
        cout << "input numbers" <<endl;
        cin >>sorted[i];
    }
    int merge[SIZE];

    mergeSort(sorted,merge,SIZE);

    for (int i=0; i<SIZE; i++) {
        cout << merge[i];
    }

    return 0;
}

void mergeSort(int numbers[], int temp[], int array_size)
{
    mergeSort(numbers, 0, array_size-1, temp);
}

void mergeSort(int a[], int low , int high,int res[])
{
    int mid = (low + high)  /2;
    if (low + 1 < high)
    {
        //  Sort sub-parts
        mergeSort(a,low,mid,res);
        mergeSort(a,mid,high,res);

        //  Merge back to "res"
        merge(a,low,mid,high,res);
    }else{
        res[low] = a[low];
    }
}

void merge(int a[], int low , int mid , int high,int res[])
{
    int i = low;
    int j = mid;
    int k = low;   //  Use "low" instead of 0.

    while (i < mid && j < high)
        if(a[i] < a[j])
            res[k++] = a[i++];
        else
            res[k++] = a[j++];

    while (i < mid)
        res[k++] = a[i++];

    while (j < high)
        res[k++] =a[j++];

    //  Copy back to "a"
    for (int c = low; c < high; c++){
        a[c] = res[c];
    }
}

最佳答案

我认为这是导致问题的原因 --

    //  Sort sub-parts
    mergeSort(a,low,mid,res);
    mergeSort(a,mid,high,res);

应该是

    //  Sort sub-parts
    mergeSort(a,low,mid,res);
    mergeSort(a,mid+1,high,res);

还有 if (low + 1 < high)应该改为if (low < high)

此外 while (i < mid && j < high)应该是 while (i <= mid && j <= high)它下面的单个 while 循环也需要用 <=

更新

关于c++ - 合并排序不正确的输出,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19441628/

相关文章:

listview - 如何在Jquerymobile中动态排序 ListView

C++ std::sort 具有相同的参数

C++ 对析构函数的 undefined reference

c++ - 函数传递后 DirectX::XMMATRIX 乘法不正确 (C++)

algorithm - 冒泡排序算法 - Scilab

c - C 排序程序中的段错误

c++ - 如何在 win32 或 MFC 中按名称获取字符串资源?

c# - 将字节数组从 Unity C# 传递到 C++ 插件

c++ - 从 C++ 调用网络服务

php - 对二维数组进行排序时保留数组键