1

Sorry if this is a stupid question, but I am pretty new to programming. I've been studying sorts, and merge sort has been giving me a headache.

void part(int arr[],int min,int max)
{
 int mid;
 if(min<max)
 {
   mid=(min+max)/2;
   part(arr,min,mid);
   part(arr,mid+1,max);
   merge(arr,min,mid,max);
 }
}

I dont understand how you can use the function part in its own definition when it's not even defined fully yet. Also, I dont really quite understand how this is working.. Please help me understand this!!

Any help greatly appreciated. Thank you.

Jarod42
  • 203,559
  • 14
  • 181
  • 302
brood915
  • 31
  • 1
  • 6
  • http://cprogrammingcodes.blogspot.com/2012/02/merge-sorting.html Here is full code just in case you want to see.. – brood915 Mar 15 '16 at 13:11
  • 6
    Check out [Recursion](https://en.wikipedia.org/wiki/Recursion_(computer_science)) – NathanOliver Mar 15 '16 at 13:12
  • ahhh that's what I assumed but was too afraid to accept it... sigh.. Time to dig it then. Thank you. – brood915 Mar 15 '16 at 13:13
  • Can you express in a better manner?. ..function part in it's own definition??? – Mathews Mathai Mar 15 '16 at 13:13
  • The function is calling itself. At the point where you write `part(arr,min,mid);`, the `part` function is known to the compiler, therefore it can be called thithout problems. – Jabberwocky Mar 15 '16 at 13:18
  • Possible duplicate of [What is recursion and when should I use it?](http://stackoverflow.com/questions/3021/what-is-recursion-and-when-should-i-use-it) – Ben Mar 15 '16 at 13:49
  • You do use `printf()`? How do you know it is "defined fully" when you call it? Code does not know and need not care. As long is it is _declared_, a function can code with it. Of course eventually, it must be defined - someplace. – chux - Reinstate Monica Mar 15 '16 at 15:24

2 Answers2

2

C++ differentiates between functions being defined and functions being declared, the difference that being to declare a function is just to know it's signature (so void part(int arr[],int min,int max). This is then sufficient information for other parts of the program to call it, without it actually needing a body of code. The definition is then where the code itself is defined.

Matt
  • 7,100
  • 3
  • 28
  • 58
1

All you need to call a function is its declaration, and a function definition also is an automatic declaration (if not already declared), and all that's needed for this automatic declaration is the function signature (return type, name, arguments, but not the full body).

Without this it would be very hard to do recursion, which is what happens when a function calls itself.

Some programmer dude
  • 400,186
  • 35
  • 402
  • 621