开发者

Riddle: Spot the serious bug in this bubble sort implementation

(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(li开发者_运维百科st.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);
    }
}


Not a bug in the strictest sense, but doing break; when you find inversion gives your sorting O(n^3) complexity, which is hardly desirable. break can just be removed.


The swap should be setting j, not i+1.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜