[英]Merge sort stops running
So my problem is, when I try to run my merge sort algorithm, it writes the random array on screen but when it tries to write the sorted array, the program stops working. 所以我的问题是,当我尝试运行合并排序算法时,它会在屏幕上写入随机数组,但是当尝试写入已排序的数组时,程序将停止工作。 I've been trying find my error but no hope so far.
我一直在尝试找到我的错误,但到目前为止没有希望。 Appreciate any help.
感谢任何帮助。
Here is my code; 这是我的代码;
#include <stdio.h>
#include <stdlib.h>
#define LEN 300
#define INF 30000
void merge (int *A, int p, int q, int r){
int i, j, k, n1 , n2 , *L, *R;
n1 = q - p + 1;
n2 = r - q;
L = (int *) malloc (n1* sizeof (int ) + 1);
R = (int *) malloc (n2* sizeof (int )) ;
for (i = 0; i < n1; i++) {
L[i] = A[p + i];
}
for (j = 0; j < n2; j++) {
R[j] = A[q + 1 + j];
}
i = j = 0;
L[n1] = R[n2] = INF ;
for (k = p; k < r; k++) {
if(L[i] <= R[j]){
A[k] = L[i];
i ++;
}
else{
A[k] = R[j];
j ++;
}
}
free(L);
free(R);
}
void mergesort (int *A, int p, int r){
int q;
if(r > (p + 1)){
q = (p + r)/2;
mergesort(A, p, q);
mergesort(A, q + 1, r);
merge(A, p, q, r);
}
}
void sorting_merge(int *A, int n){
mergesort (A, 0, LEN);
}
int main (){
int i, *n;
n = malloc ( sizeof (int )*LEN );
srand (666) ;
for (i = 0; i < LEN ; i++) {
n[i] = rand() % 1000;
printf ("%d ", n[i]);
}
printf ("\n");
sorting_merge(n, LEN);
for (i = 0; i < LEN ; i++) {
printf ("%d ", n[i]);
}
printf ("\n");
free (n);
system("PAUSE");
return 1;
}
L[n1] = R[n2] = INF ;
accesses beyond the allocated memory. 访问超出分配的内存。 Your allocation should read
您的分配应显示为
L = malloc((n1 + 1) * sizeof (int));
R = malloc((n2 + 1) * sizeof (int));
if you really want to access index n1
and n2
. 如果您确实要访问索引
n1
和n2
。
I haven't checked anything else, that was the first thing that sprang in my eyes. 我什么都没检查,那是我眼中闪现的第一件事。
change to 改成
L = (int *) malloc((n1+1)* sizeof(int));
R = (int *) malloc((n2+1)* sizeof(int));
for (k = p; k <= r; k++) {//include r
if(r > p){
void sorting_merge(int *A, int n){//call sorting_merge(n, LEN); note LEN is out range
mergesort (A, 0, n-1);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.