xdaiqy
jggybf
采纳率21.4%
2019-09-01 12:59 阅读 1.1k

C语言归并排序问题 求解答

请大家帮我看一下这段代码的问题,谢谢了

/*先拆分,再两两归并!*/

#include<stdio.h>
#define MAXSIZE 10

/*归并后的数据存入list1*/


void merging(int *list1, int list1_size, int *list2, int list2_size)//归并代码
{
    int temp[MAXSIZE];
    int i, j, k;
    int m;
    i =j =k =0;


    while(i < list1_size && j < list2_size)
    {
        if(list1[i] < list2[i])
        {
            temp[k++] = list1[i++];
        }
        else
        {
            temp[k++] = list2[j++];
        }
    }
    while(i < list1_size)
    {
        temp[k++] = list1[i++];
    }
    while(j < list2_size)
    {
        temp[k++] = list2[j++];
    }
    for(m=0; m < (list1_size + list2_size); m++)
    {
        list1[m] = temp[m];
    }
}



void MergeSort(int k[] , int n)//递归拆分代码
{
    if (n > 1)
    {
        int *list1 = k;
        int list1_size = n/2;
        int *list2 = k + n/2;
        int list2_size = n - list1_size; 

        MergeSort(list1, list1_size);
        MergeSort(list2, list2_size);

        merging(list1, list1_size, list2, list2_size);//归并
    }


}
int main()
{
    int i, a[10]={2,4,6,8,0,9,7,5,3,1};

    MergeSort(a,10);

    printf("排序后的结果是:");

    for(i=0;i<10;i++)
    {
        printf("%d ",a[i]);
    }

    printf("\n");

    return 0;
}

图片说明

  • 点赞
  • 写回答
  • 关注问题
  • 收藏
  • 复制链接分享

2条回答 默认 最新

  • 已采纳
    qq_40946921 Italink 2019-09-01 16:47
    while (i < list1_size && j < list2_size)
        {
            if (list1[i] < list2[j])   //把j写成i了
            {
                temp[k++] = list1[i++];
            }
            else
            {
                temp[k++] = list2[j++];
            }
        }
    
    点赞 1 评论 复制链接分享
  • qq_45594650 qq_45594650 2019-09-02 00:19

    lis1i和list2i比较
    然后tempk=list1i或tempk=list2j
    为啥是j不是i

    点赞 评论 复制链接分享

相关推荐