我正在尝试使用以下合并排序函数对数组进行排序。但是它没有给我预期的输出。它不会打印出正确/预期的输出,即
输入: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];
}
}