Im having trouble with my linked list selection sort below:
public static void selectionSort(LN l) {
for (LN r = l; r != null; r = r.next) {
LN min = r;
for (LN s = r; s != null; s = s.next)
if (min.value > s.value)
min = s;
LN temp = r;
r.value = min.value;
min.value = temp.value;
}
}
So for the input: 10, 4,6,2,1,7,9,8,5,3
I get the output: 1,1,1,1,1,3,3,3,3,3
What’s wrong with the sort here?
This:
is wrong. By setting
tempequal tor, you’re actually causing them to refer to the same object; so modifyingr.valueis equivalent to modifyingtemp.value. So the above ends up not really modifyingmin.value; it just setsmin.valueto what it already was.Instead, you should write: