为什么我的合并排序最终将随机4放置
Why does my merge sort put a random 4 in the end?
我的合并排序无法正常工作,它可以对第一个值进行排序,但是最后一个值" 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 = 4
,R[4]
是出乎意料的。
相关文章:
- 为什么随机数生成器不在void函数中随机化数字,而在main函数中随机化
- 为什么 Serial.println(<char[]>);返回随机字符?
- 字符串-C++后显示的随机字符
- 循环中的随机函数
- 在c++构造函数中使用随机字符串生成器
- Constexpr替代了新的放置方式,可以让内存中的对象保持未初始化状态
- 使用std::mt19937从字符串中返回一个随机单词
- 为什么std::condition_variable notify_all的工作速度比notify_one快(对于随机请
- 如何在C++中高效地构造随机骰子
- 在类中使用随机生成器时出现性能问题
- 在将数字随机生成为数组期间从内存输出随机数的数组
- C++在乘法图中放置随机值(嵌套循环)
- 如何在网格中放置随机字符
- 评估 NxN 矩阵中最大正方形的面积,该矩阵最多包含 K 个(随机放置)
- C 阵列随机放置1s
- 为什么我的合并排序最终将随机4放置
- 如何在游戏板中放置一艘随机飞船
- 对象在轨迹上的随机放置
- 在二维数组中随机放置一个数组
- boost::spirit-从随机放置的条目中解析AST样式