谜语:找出冒泡排序实现中的严重错误
(不,这不是作业,我只是发现了这个错误,并认为在这里分享它可能会有用)
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);
}
}
(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);
}
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
从严格意义上讲,这不是一个错误,但是当您发现反转时执行
break;
会给您的排序带来O(n^3)
复杂性,这是不可取的。break
可以直接删除。Not a bug in the strictest sense, but doing
break;
when you find inversion gives your sortingO(n^3)
complexity, which is hardly desirable.break
can just be removed.swap
应该设置 j,而不是 i+1。The
swap
should be setting j, not i+1.