我已经用Python编程了一年多了,我刚回到C ++,学习了一些基本的算法。我开始使用合并排序,但它给了我一个分段错误。非常感谢帮助。我想我调试了它发生的地方,但我无法理解为什么。
#include <iostream>
using namespace std;
void* merge(int array1[], int array2[], int low, int mid, int high){
int i, j, k;
for (i = low,j = mid, k = low; i < mid, j < high; k++){
if (array1[i] < array1[j]){
array2[k] = array1[i];
i++;
}
else{
array2[k] = array1[j];
j++;
}
}
if (i == mid){
for (; j < high; j++, k++){
array2[k] = array1[j];
}
}
else{
for (; i < mid; i++, k++){
array2[k] = array1[i];
}
}
void* merge_sort(int array1[], int copy[], int low, int high){
int mid;
int range = high - low;
if (range == 1)
copy[low] = array1[low];
else{
mid = low + range/2;
merge_sort(array1, copy, low, mid);
// Segmentation error seems to be here.
merge_sort(array1, copy, mid, high);
}
merge(array1, copy, low, mid, high);
}
int main()
{
int n, temp;
cout << "How many numbers do you want to enter?" << endl;
cin >> n;
int numarray[n];
for (int i = 0; i < n; i++){
cin >> numarray[i];
}
int dumarray[n]; // Used for filling elements from merge sort
merge_sort(numarray, dumarray, 0, n);
cout << "Merge Sort" << endl;
for (int i = 0; i < n; i++){
cout << dumarray[i] << endl;
}
return 0;
}
编辑:
#include <iostream>
using namespace std;
void merge_sort(int [], int [], int, int);
void merge(int array1[], int array2[], int low, int mid, int high){
int i, j, k;
for (i = low,j = mid, k = low; i < mid, j < high; k++){
if (array1[i] < array1[j]){
array2[k] = array1[i];
i++;
}
else{
array2[k] = array1[j];
j++;
}
}
if (i == mid){
for (; j < high; j++, k++){
array2[k] = array1[j];
}
}
else{
for (; i < mid; i++, k++){
array2[k] = array1[i];
}
}
}
void merge_sort(int array1[], int copy[], int low, int high){
int mid;
int range = high - low;
mid = low + range/2;
if (range == 1)
copy[low] = array1[low];
else{
mid = low + range/2;
merge_sort(array1, copy, low, mid);
merge_sort(array1, copy, mid, high);
merge(array1, copy, low, mid, high);
}
}
int main(){
int n, temp;
cout << "How many numbers do you want to enter?" << endl;
cin >> n;
int numarray[n];
for (int i = 0; i < n; i++){
cin >> numarray[i];
}
int dumarray[n];
merge_sort(numarray, dumarray ,0, n);
for (int i = 0; i < n; i++){
cout << dumarray[i] << endl;
}
}
答案 0 :(得分:1)
中值的计算似乎是错误的。尝试计算mid为
mid = low + (high-low)/2
修改:将merge(array1, copy, low, mid, high);
移到else括号内。
else
{
mid = low + range/2;
merge_sort(array1, copy, low, mid);
merge_sort(array1, copy, mid, high);
merge(array1, copy, low, mid, high);
}
merge
函数也有很多错误。条件检查初始for循环
i < mid, j < high
以逗号分隔,这意味着它只检查j < high
并放弃i的条件检查。