# Selection Sort recursive java code

• 07-12-2010, 08:33 AM
myst
Selection Sort recursive java code
I don't understand something about the selection sort recursive java code.

Code:

```void selection sort(int[]data, int lo, int hi){     if (lo < hi){           swap(data, lo, findMaximum(...));           selectionSort(data, lo+1, hi);     } }```
(findMaximum finds maximum value, swap swaps maximum value with lo)

I think I just dont know what lo and hi are... I would just assume that lo=a[0] and hi=a[length-1]. So if we would have an array

3 2 7 1

lo=a[0] and hi=a[3]. So since a[0] is always > a[3], selectionSort would never be able to swap the 7... (even if hi=a[1] it would never be able to swap the 7...)
• 07-12-2010, 09:24 AM
JosAH
Quote:

Originally Posted by myst
I don't understand something about the selection sort recursive java code.

Code:

```void selection sort(int[]data, int lo, int hi){     if (lo < hi){           swap(data, lo, findMaximum(...));           selectionSort(data, lo+1, hi);     } }```
(findMaximum finds maximum value, swap swaps maximum value with lo)

I think I just dont know what lo and hi are... I would just assume that lo=a[0] and hi=a[length-1]. So if we would have an array

3 2 7 1

lo=a[0] and hi=a[3]. So since a[0] is always > a[3], selectionSort would never be able to swap the 7... (even if hi=a[1] it would never be able to swap the 7...)

Nonono, lo and hi are array index values, so you start the method with lo= 0 and hi= 3. You find the maximum in the elements [lo,hi] and swap it with the element at index lo; then you repeat the sort with the (sub)array [lo+1,hi] etc. etc.

kind regards,

Jos
• 07-12-2010, 10:02 AM
myst
oooo, that makes a lot more sense...

Thanks JosAh, again...
• 07-12-2010, 10:08 AM
JosAH
Quote:

Originally Posted by myst
oooo, that makes a lot more sense...

Thanks JosAh, again...

You're welcome of course; notice that I've edited my previous reply, there was a typo in there: you have to find the maximum of all elements in the (sub)array [lo, hi] (I accidentally wrote [lo+1,hi]) and swap it with the element at index lo. Then you repeat the process with the (sub)array [lo+1,hi].

kind regards,

Jos