14,177,097 members
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

## 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);
//localMax = ????

}
return localMax ;
}```
AliGharibi 16-Dec-15 12:41pm

So all the problem was because i didn't define a variable inside the function ?

## 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:
AliGharibi 16-Dec-15 12:38pm

sorry i made a mistake its find_max there but still not working

Top Experts
Last 24hrsThis month
 Richard MacCutchan 100 Patrice T 60 Maciej Los 50 F-ES Sitecore 40 Maximilien 40
 OriginalGriff 4,664 Richard MacCutchan 2,050 Patrice T 1,577 Gerry Schmitz 1,252 phil.o 1,248