我是新來的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