【发布时间】:2017-10-13 15:56:03
【问题描述】:
我是 C++ 新手,正在尝试开发合并排序的代码。我用大小为 15 的样本数组对其进行了测试,但代码给出的答案是不正确的。我不知道出了什么问题。这是我的代码:
#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;
}
initiation[]的输出,也就是fin[]是:
5,4,67,15,3,2,0,200,1,2,9,8,98,6,44,
【问题讨论】:
-
调试器是解决此类问题的正确工具。 在询问 Stack Overflow 之前,您应该逐行浏览您的代码。如需更多帮助,请阅读How to debug small programs (by Eric Lippert)。
-
@Tas 以下是完整的股票评论供参考:解决此类问题的正确工具是您的调试器。在 Stack Overflow 上询问之前,您应该逐行检查您的代码。如需更多帮助,请阅读How to debug small programs (by Eric Lippert)。至少,您应该 [编辑] 您的问题,以包含一个重现您的问题的 Minimal, Complete, and Verifiable 示例,以及您在调试器中所做的观察。
-
@πάνταῥεῖ 不确定最好的提问方式,但是是的,我完全偷走了你的评论(我希望没关系)!我有整个评论供参考,但省略了最后一部分,因为这或多或少是一个 mcve
-
@Tas 当然没关系,因为这是一个普遍的问题。我只是给了你到目前为止我一直在开发它的全部内容。