我是新来的c + +并试图开发合并排序代码。我用一个大小为15的样本数组对它进行了测试,但代码发布的答案并不正确。我无法弄清楚发生了什么问题。这里是我的代码:C++合并排序问题
#include <stdlib.h>
#include <stdio.h>
#include <iostream>
#include <string>
#include <fstream>
#include <vector>
#include <unistd.h>
#include <cstdlib>
using namespace std;
//two arrays, input
int initial[15] = {200,1,2,9,8,98,6,44,5,4,67,15,3,2,0};
//for output
int fin[15];
void sort(int* ini, int left, int right, int m);
//saperate the input in a recursion
void devide(int* ini, int left, int right){
int m;
if(left < right){
m = (left + right)/2;
devide(ini, left, m);
devide(ini, m+1, right);
sort(ini, left, right, m);
}
}
//sorting
void sort(int* ini, int left, int right, int m){
//first half, start at the first element in the input array
int first_h = left;
//second half, start at the first element after the
// middle element in the input array
int second_h = m+1;
//index for output array
int out = left;
//comparing, if both half of array have element
while(first_h <= m && second_h <= right){
//put the smaller in the the output array
if(initial[first_h] < initial[second_h]){
fin[out] = initial[first_h];
first_h++;
}
else{
fin[out] = initial[second_h];
second_h++;
}
out++;
}
//if one of half of input is empty, put the rest element into the
// output array
while(first_h <= m){
fin[out] = initial[first_h];
out++;
first_h++;
}
while(second_h <= right){
fin[out] = initial[second_h];
out++;
second_h++;
}
}
int main(){
devide(initial, 0, 14);
for(int i =0; i<15; i++){
cout<<fin[i];
cout<<",";
}
return 0;
}
启动[]的输出,这是鳍[]是:
5,4,67,15,3,2,0,200,1,2,9,8,98,6,44,
解决此类问题的正确工具是您的调试器。你应该逐行遍历你的代码,在堆栈溢出时询问_before_。如需更多帮助,请阅读[如何调试小程序(由Eric Lippert撰写)](https://ericlippert.com/2014/03/05/how-to-debug-small-programs/)。 – Tas
@Tas以下是完整的参考评论:_解决此类问题的正确工具是您的调试器。在*堆栈溢出问题之前,您应该逐行执行您的代码。如需更多帮助,请阅读[如何调试小程序(由Eric Lippert撰写)](https://ericlippert.com/2014/03/05/how-to-debug-small-programs/)。至少,您应该\编辑您的问题,以包含一个[最小,完整和可验证](http://stackoverflow.com/help/mcve)示例,该示例再现了您的问题,以及您在debugger._ –
@πάνταῥεῖ不确定询问的最佳方式,但是我完全偷了你的评论(我希望没关系)!我有整个评论供参考,但省略了最后一部分,因为这或多或少是一个mcve – Tas