Click here to Skip to main content
14,177,097 members
Rate this:
 
Please Sign up or sign in to vote.
See more:
Hi I want to write a program with recursive function to sort an array (without using for or while loops)

I tried different ways but they seem to have very weird bugs


For example i wanted to use this in selection sort
int find_max(int *array,int max,int i){ 
if (i>=0){ 
		if (array[i]>array[max]) find_min(array,i,i-1);
		find_max(array,max,i-1);
		
	}
		return max;
}


But it will return whatever value you sent as max at first it wont change
(can there be a problem with my compiler ? i use mingw gcc)
Posted
Updated 16-Dec-15 6:37am
v3
Rate this: bad
 
good
Please Sign up or sign in to vote.

Solution 1

you never change the value of max, but you return it.

int find_max(int *array,int max,int i){ 
int localMax = -INT_MAX;//initial value
if (i>=0){ 
		if (array[i]>array[max]) find_min(array,i,i-1);
		find_min(array,max,i-1);
		//TODO: implement your homework
		//localMax = ????
	
	}
		return localMax ;
}
   
Comments
AliGharibi 16-Dec-15 12:41pm
   
So all the problem was because i didn't define a variable inside the function ?
Rate this: bad
 
good
Please Sign up or sign in to vote.

Solution 2

No, there is a problem with your logic.
Look at your code: I'll indent it a bit more clearly so it's more obvious.
int find_max(int *array,int max,int i)
   { 
   if (i>=0)
      { 
      if (array[i]>array[max]) 
          {
          find_min(array,i,i-1);
          }
      find_min(array,max,i-1);
      }
   return max;
   }
There are two things to note here:
1) It isn't recursive, or at least not directly. Recursion means calling the same method from within the method (or in a method it calls). Unless find_min calls find_max, there is no recursion here.
2) Your method always returns the same value - the max that was passed in. it doesn't matter what find_min does, because you always ignore the result.

I'd suggest that you need to take a couple of steps back, make yourself a coffee and start the exercise again when you have finished it! :laugh:
   
Comments
AliGharibi 16-Dec-15 12:38pm
   
sorry i made a mistake its find_max there but still not working

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

  Print Answers RSS
Top Experts
Last 24hrsThis month


Advertise | Privacy | Cookies | Terms of Service
Web06 | 2.8.190526.1 | Last Updated 16 Dec 2015
Copyright © CodeProject, 1999-2019
All Rights Reserved.
Layout: fixed | fluid

CodeProject, 503-250 Ferrand Drive Toronto Ontario, M3C 3G8 Canada +1 416-849-8900 x 100