为什么我的合并排序最终将随机4放置

Why does my merge sort put a random 4 in the end?

本文关键字:随机 放置 我的 合并 排序 为什么      更新时间:2023-10-16

我的合并排序无法正常工作,它可以对第一个值进行排序,但是最后一个值" 7"获得了" 4"。

我似乎无法弄清楚原因。

我已经尝试将n,q,p值调整为0个索引数组,但这无济于事。

我还尝试调整N1和N2值,但没有运气

#include <iostream>
#include <limits>
using namespace std;

// p = start of array
// q = center of array
// r = end of array
int A[8] = {2,4,5,7,1,2,3,6};
int p = 1; //Start value of the array
int q = 4; //Middle value of the array
int r = 8; //End value of the array
int L[4]; //Making a new array with 4 slots
int R[4]; //Making a new array with 4 slots

int n1 = q-p+1; //Range of the left array
int n2 = r-q; //Range of the right array
int main(){
for (int i = 0; i < n1; i++){ //Putting the first 4 values in the 
"left" array
    L[i] = A[p+i-1];
}
for (int j = 0; j < n2; j++){ //Putting the last 4 values in the 
"right" array
    R[j] = A[q+j];
}
int m = 0;
int n = 0;
for (int z = 0; z < 8; z++){ //The sorting algorithm
    if (L[m] <= R[n]){
        A[z] = L[m];
        m = m+1;
    }
    else{
        A[z] = R[n];
        n = n+1;
    }
}
cout << "Left array: ["; //Printing out the arrays
for (int k = 0; k < 4; k++){
    cout << L[k] << " ";
}
cout << "]"<< "n";
cout << "Right array: [";
for (int k = 0; k < 4; k++){
    cout << R[k] << " ";
}
cout << "]"<< "n";
cout << "Sorted A: [";
for (int k = 0; k < 8; k++){
    //cout << L[k] << 'n';
    //cout << R[k] << 'n';
    cout << A[k] << " ";
}
cout << "]"<< "n";
return 0;
}

给出输出:

Left array: [2 4 5 7 ]
Right array: [1 2 3 6 ]
Sorted A: [1 2 2 3 4 5 6 4 ]

,因为您不限制L和R的索引,在最后一个比较中,R数组溢出。n = 4R[4]是出乎意料的。