Riddle: Spot the serious bug in this bubble sort implementation

Posted by ripper234 on Stack Overflow See other posts from Stack Overflow or by ripper234
Published on 2010-12-31T21:26:43Z Indexed on 2010/12/31 21:54 UTC
Read the original article Hit count: 338

Filed under:
|
|
|

(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);
    }
}

© Stack Overflow or respective owner

Related posts about java

Related posts about sorting