简体   繁体   中英

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 .

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);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM