简体   繁体   English

合并排序逻辑错误

[英]Merge Sort Logical Error

I was actually working on assignment and found an online code on merge sort and edited it a bit, but It is giving logical error, the answer (sorted array) isn't showing up instead it shows only first 2 numbers correctly(sometimes) and I can't fix it, if you could check on my code and give me a few ideas. 我实际上是在分配作业,发现了一个关于合并排序的在线代码,并对其进行了一些编辑,但是它给出了逻辑错误,没有显示答案(排序数组),而是正确地仅显示前两个数字,并且如果您可以检查一下我的代码并给我一些想法,我将无法解决。

#include<stdio.h>

int arr[20];       // array to be sorted

int main()
{

  int n,i;
  clrscr();
  printf("Enter the size of array\n");  // input the elements
  scanf("%d",&n);
  printf("Enter the elements:");
  for(i=0; i<n; i++)
    scanf("%d",&arr[i]);

  merge_sort(arr,0,n-1);  // sort the array

  printf("Sorted array:");  // print sorted array
  for(i=0; i<n; i++)
    printf("%d",arr[i]);
   getch();
  return 0;
}

int merge_sort(int arr[],int low,int high)
{
  int mid; int i;
  if(low<high) {

    mid=(low+high)/2;
    // Divide and Conquer
    merge_sort(arr,low,mid);
    merge_sort(arr,mid+1,high);
    // Combine


    merge(arr,low,mid,high);
  }

  return 0;
}

int merge(int arr[],int l,int m,int h)
{
  int arr1[10],arr2[10];  // Two temporary arrays to
  //hold the two arrays to be merged
  int n1,n2,i,j,k,z;

    i=0,j=0;

    for(z=l;z<=m;z++)
    {
        arr1[i]=arr[z];
        i++;
    }
    for(z=m+1;z<=h;z++)
    {
        arr2[j]=arr[z];
        j++;
    }




  n1=i;
  n2=j;
  i=0;
  j=0;
  for(k=l; k<=h; k++)
  { //process of combining two sorted arrays

    if(i<n1 && j<n2)
    {
     if(arr1[i]<=arr2[j])
     {
          arr[k]=arr1[i++];
          }
    else
         arr[k]=arr2[j++];
     }
     else if(i>=n1)
     {
      arr[k]=arr[j++];
     }
     else
     {
     arr[k]=arr[i++];
     }


  }

  return 0;
}

wrong part 错误的部分

     else if(i>=n1)
     {
      arr[k]=arr[j++];
     }
     else
     {
     arr[k]=arr[i++];
     }

corrected (use arr1 and arr2 instead of arr as the source of assignments) 更正的(使用arr1arr2而不是arr作为分配源)

     else if(i>=n1)
     {
      arr[k]=arr2[j++];
     }
     else
     {
     arr[k]=arr1[i++];
     }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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