Riddle: Spot the serious bug in this bubble sort implementation
- by ripper234
(No, this isn't a homework assignment, I just found the bug and thought it might be useful to share it here)
import java.util.List;
public class BubbleSorter {
public <T extends Comparable<T>> void sort(List<T> list) {
while (true) {
boolean didWork = false;
for (int i = 0; i < list.size() - 1; ++i) {
if (list.get(i).compareTo(list.get(i + 1)) > 0) {
swap(list, i, i + 1);
didWork = true;
break;
}
}
if (!didWork)
return;
}
}
private static <T> void swap(List<T> list, int i, int j) {
T tmp = list.get(i);
list.set(i, list.get(j));
list.set(j, tmp);
}
}