algorithm - merge sort using recursion in c languaage -
#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 size of array\n"); scanf("%d",&n); printf("enter elements:\n"); for(i=0; < 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; < 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; < 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 program taking input array of size 7.so main() merge_sort(arr,0,6) passed respective function after condition checked if(0<6) there mid becomes 3 ,then there recursive call low = 0 , mid = 3,then time mid 1 again recursive call with(arr,0,1) ..and on till low , mid equals 0 ,then there if condition fails because if(0<0) not true
but , able understand how merge_sort(arr,mid+1,high); being called?but program runs fine .please explain how compiler calling merge_sort(arr,mid+1,high)
based on comments, real question is: given 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); // 1 merge(arr,low,mid,high); } }
how can indicated line ever reached, since line before recurses same function?
within conditional block, value of mid
first set value between low , high points. mid
becomes high
next iteration, bringing low
, high
closer together. if(low < high)
fail, terminating leg of recursion.
Comments
Post a Comment