问题
#include<stdio.h>
#include<conio.h>
int arr[20];
void main()
{
int n,i;
clrscr();
printf("\n\t\t\t------Merge Sorting------\n\n");
printf("Enter the size of array\n");
scanf("%d",&n);
printf("Enter the elements:\n");
for(i=0; i < n; i++)
{
scanf("%d",&arr[i]);
}
merge_sort(arr,0,n-1);
printf("\n\n\t\t\t-----Merge Sorted Elements-----\n\n");
printf("Sorted array:\t");
for(i=0; i < n; i++)
{
printf("\t%d",arr[i]);
}
getch();
}
int merge_sort(int arr[],int low,int high)
{
int mid;
if(low < high)
{
mid=(low+high)/2;
merge_sort(arr,low,mid);
merge_sort(arr,mid+1,high);
merge(arr,low,mid,high);
}
}
int merge(int arr[],int l,int m,int h)
{
int arr1[10],arr2[10];
int n1,n2,i,j,k;
n1=m-l+1;
n2=h-m;
for(i=0; i < n1; i++)
{
arr1[i]=arr[l+i];
}
for(j=0; j < n2; j++)
{
arr2[j]=arr[m+j+1];
}
arr1[i]=9999;
arr2[j]=9999;
i=0;
j=0;
for(k=l; k <=h; k++)
{
if(arr1[i]<=arr2[j])
arr[k]=arr1[i++];
else
arr[k]=arr2[j++];
}
}
if in this program i am taking input an array of size 7.so from main() merge_sort(arr,0,6) is passed to the respective function after that condition is checked if(0<6) then there mid becomes 3 ,then there is a recursive call with low = 0 and mid = 3,then this time mid is 1 again recursive call with(arr,0,1) ..and so on till low and mid equals 0 ,then there if condition fails because if(0<0) is not true
but and i am able to understand how merge_sort(arr,mid+1,high); is being called?but this program runs fine .please explain how the compiler is calling merge_sort(arr,mid+1,high)
回答1:
Based on comments, the real question is: given this bit of recursive code:
int merge_sort(int arr[],int low,int high)
{
int mid;
if(low < high)
{
mid=(low+high)/2;
merge_sort(arr,low,mid);
merge_sort(arr,mid+1,high); // THIS ONE
merge(arr,low,mid,high);
}
}
How can the indicated line ever be reached, since the line before it recurses into the same function?
Within the conditional block, the value of mid
is first set to a value between the low and high points. This mid
then becomes the high
for the next iteration, bringing low
and high
closer together. Eventually if(low < high)
will fail, terminating that leg of recursion.
来源:https://stackoverflow.com/questions/23058747/merge-sort-using-recursion-in-c-languaage