I am new to programming, Please explain me the working of the below recursion function. The function is called recursively twice, Will the statements after the 1st recursive call gets executed?
void sort(int low, int high) {
int mid;
if(low < high) {
mid = (low + high) / 2;
sort(low, mid);
sort(mid+1, high);
merging(low, mid, high);
} else {
return;
}
}
void main()
{
sort(0, 10);
}
see the Recursion example link from stack overflow. Examples of Recursive functions
What are you trying to achieve in the code? A recursion function should call the function itself and it should have the condition to stop otherwise it will go in infinite loop. The code you have written called the same function twice and which is not correct. You should call the function once and with stop condition.
Lets go line by line
if(low < high)
Since 0 < 10 then mid will be 5 : because of mid = (low + high) / 2;
. sort(mid+1, high);
of your code sort will be called again this time for low = 1 and high also = 1. Consider this as a stack, first push sort(0,10)
then => sort(0,5)
then => sort(0,2)
then => sort(0,1)
then => sort(0,0)
Now since sort(0,0)
finished executing it will be removed from the stack and sort(0,1)
will continue. So it should look like this
sort(0,10)
=> sort(0,5)
=> sort(0,2)
=> sort(0,1)
Again in the fifth line of the sort(0,1)
the call to sort()
is there, so again sort will be pushed to this stack:
sort(0,10)
=> sort(0,5)
=> sort(0,2)
=> sort(0,1)
=> sort(1,1)
This will goes on and finally the call to the sort(0,10)
will finish executing and you will get your desired outcome.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.