# Thread: recursive selection sort function

1. ## recursive selection sort function

I'm having a problem with a function that uses the selection-sorting algorithm using recursion rather than a loop. I start out with an integer array with 30 elements:

199 173 175 28 175 102 114 129 199 125
138 95 163 121 45 156 16 70 147 16
110 27 127 78 97 130 3 35 152 19

and when I run the function using this:
selection_sortup(&array[0], 30);

I end up with this:

3 3 16 19 27 28 35 45 70 78
95 97 102 110 114 121 125 127 129 130
137 137 138 147 152 156 163 173 175 175

Here's the function:

Code:
```void selection_sortup(int *p, int n)
{

int i, largest = 0, temp, temp_index;
if (n == 0)
return;
/* finds the largest value in array - saves it and its index */
for(i = 0; i < n; i++){
if (largest < *(p+i)){
largest = *(p+i);
temp_index = i;
}
}

/* copies the last element of the array into temp variable */
temp = *(p+n);
/* switches the two */
*(p+temp_index) = temp;
*(p+n) = largest;
/* recursive call - predecrements n */
selection_sortup(p, --n);
}```
Any help would be greatly appreciated.

2. Help with what? That array seems sorted to me...

3. ## Re: recursive selection sort function

Code:
```   /* copies the last element of the array into temp variable */
temp = *(p+n);
/* switches the two */
*(p+temp_index) = temp;
*(p+n) = largest;```
The last element in the array is *(p+n-1).

4. ## Re: Re: recursive selection sort function

Originally posted by Dave_Sinkula
The last element in the array is *(p+n-1).
Yay, it now works correctly! Thanks for the help!