Thread: Selection Sort recursive java code

1. Member
Join Date
May 2010
Posts
44
Rep Power
0

Selection Sort recursive java code

I don't understand something about the selection sort recursive java code.

Java 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...)

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

Java 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
Last edited by JosAH; 07-12-2010 at 10:05 AM.

3. Member
Join Date
May 2010
Posts
44
Rep Power
0
oooo, that makes a lot more sense...

Thanks JosAh, again...

4. 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

Posting Permissions

• You may not post new threads
• You may not post replies
• You may not post attachments
• You may not edit your posts
•