私は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,
このような問題を解決する適切なツールは、デバッガです。 Stack Overflowを尋ねる前に、コードをステップバイステップで実行する必要があります。詳しいヘルプは、[小さなプログラムをデバッグする方法(Eric Lippert)](https://ericlippert.com/2014/03/05/how-to-debug-small-programs/)を参照してください。 – Tas
@Tas refernceの完全なコメントは次のとおりです:このような問題を解決するための正しいツールは、デバッガです。スタックオーバーフローを尋ねる前に、コードを一行ずつ進める必要があります。詳しいヘルプは、[小さなプログラムをデバッグする方法(Eric Lippert)](https://ericlippert.com/2014/03/05/how-to-debug-small-programs/)を参照してください。最低限、問題を再現する[最小、完全、および検証可能](http://stackoverflow.com/help/mcve)の例と、その問題を再現するためのdebugger._ –
@πάνταῥεῖは尋ねる最善の方法は確かではありませんでしたが、はい、私は完全にあなたのコメントを盗んでしまいました(私はそれが問題ないと思います)!私は参照のために全面的なコメントを持っていますが、これは多かれ少なかれmcveなので最後の部分は省略しました – Tas