使用Collections.sort()方法和对列表进行排序的实现之间有什么区别?哪个更快?
public static void listSortingDoubleForLoop(List<Integer> list)
{
for (int i = 0; i < list.size(); i++) {
for (int j = i+1; j < list.size(); j++) {
if (list.get(i).compareTo(list.get(j)) > 0) {
Collections.swap(list, i, j);
}
}
}
}
解决方法:
您的两个嵌套的for循环需要二次运行时间(即O(n2)).
Collections.sort()的JDK实现使用更有效的O(nlogn)排序算法.
例如,这是JDK 8的实现说明:
This implementation is a stable, adaptive, iterative mergesort that requires far fewer than n lg(n) comparisons when the input array is partially sorted, while offering the performance of a traditional mergesort when the input array is randomly ordered. If the input array is nearly sorted, the implementation requires approximately n comparisons.
传统合并排序的性能为O(nlog(n)).