Click here to Skip to main content
15,887,585 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
this is a function that split the array into subsets recursively ..
My problem is that I don't understand how the function will recurse twice..Isn't is supposed to recurse first with new arguments(a,i,mid).. how will it then return and take new arguments(a,mid+1,j) if it already broke to recurse at first place?

What I have tried:

void mergesort(int a[],int i,int j)
{
int mid;
if(i<j)
{
mid=(i+j)/2;
mergesort(a,i,mid); //left recursion
mergesort(a,mid+1,j); //right recursion//my problem//
merge(a,i,mid,mid+1,j); //merging of two sorted sub-arrays
}
}
Posted
Updated 8-Nov-17 11:36am

1 solution

Quote:
I don't understand how the function will recurse twice.

Your code don't recurs twice at same time, it recurs 2 times in sequence.

C++
mergesort routine execution
  do stuff
  call mergesort(a,i,mid); // first recurs
  resume // resume execution when first recurs is finished
  do stuff
  call mergesort(a,mid+1,j); // second recurs
  resume // resume execution when second recurs is finished
  do stuff


Use the debugger to see the code execute
There is a tool that allow you to see what your code is doing, its name is debugger. It is also a great learning tool because it show you reality and you can see which expectation match reality.
When you don't understand what your code is doing or why it does what it does, the answer is debugger.
Use the debugger to see what your code is doing. Just set a breakpoint and see your code performing, the debugger allow you to execute lines 1 by 1 and to inspect variables as it execute.

Debugger - Wikipedia, the free encyclopedia[^]

Mastering Debugging in Visual Studio 2010 - A Beginner's Guide[^]
Basic Debugging with Visual Studio 2010 - YouTube[^]
The debugger is here to show you what your code is doing and your task is to compare with what it should do.
There is no magic in the debugger, it don't find bugs, it just help you to. When the code don't do what is expected, you are close to a bug.
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900