在c中调试合并排序实现

时间:2014-07-24 22:44:52

标签: c

我正在调试合并排序的c实现。出于某种原因,r(合并中)的值为nan。然而,n2(定义为(int) (r - q))定义明确。为什么r == nan

#include <stdio.h>
#include <limits.h>
#include <math.h>


void merge(int *A,float p,float q,float r)
{
    float n = r - p + 1; /* number of elements in array A */
    int n1 = (int) (q - p + 1);
    int n2 = (int) (r - q);
    printf("n2 = %d\n",n2);
    int  i, j;
    float k;

    int *L, *R;
    for (i = 1; i <= n1; i++){
        L[i] = A[(int) (p + i - 1)];
    }

    for (j = 1; j < n2; j++){
        R[j] = A[(int) (q + j)];
    }

    L[n1+1] = INT_MAX;
    R[n2+1] = INT_MAX;

    i = 1;
    j = 1;

    printf("p = %f\n",p);
    printf("r = %f\n",r);

    for (k = p; k <= r; k++){
        printf("k=%f\n",k);
        if (L[i] <= R[j]){
            A[(int) k] = L[i];
            i += 1;
        }

        else{
            A[(int) k] = R[j];
            j += 1;
        }
    }
}

void merge_sort(int *A, float p, float r)
{
    int i;
/*  for (i=0; i<=r-p;i++){
        printf("%d\n",A[i]);
    }*/
    float q;
    if (p < r){
    /*  printf("merge_sort p = %d\n",p);
        printf("merge_sort r = %d\n",r);*/
        q = floor((p + r)/2);
/*      printf("q = %f\n",q);*/
        merge_sort(A, p, q);
        merge_sort(A, q+1, r);
/*      printf("done\n");*/
        merge(A, p, q, r);
    }
}


int main()
{
    int x, c, *array;
    int n;

    printf("Enter number of elements\n");
    scanf("%d",&n);

    printf("Enter %d elements\n",n);

    for (c = 0; c < n; c++){
        scanf("%d", &array[c]);
    }

    merge_sort(array, 0, n-1);

    for (c = 0; c < n; c++){
        printf("%d\n", array[c]);
    }
}

1 个答案:

答案 0 :(得分:2)

int *L, *R;
for (i = 1; i <= n1; i++){
    L[i] = A[(int) (p + i - 1)];
}

LR未经初始化

array相同:

   int x, c, *array;

   ...

   for (c = 0; c < n; c++){
       scanf("%d", &array[c]);