在C中调试合并排序实现

大树

我正在调试合并排序的ac实现。出于某种原因,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]);
    }
}
大卫·拉涅里(David Ranieri)
int *L, *R;
for (i = 1; i <= n1; i++){
    L[i] = A[(int) (p + i - 1)];
}

L并且R未初始化使用

相同array

   int x, c, *array;

   ...

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

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章