我发现java.util.Arrays.sort(Object[])使用了两种排序算法(在JDK1.6中)。
伪代码:
if(array.length<7)
insertionSort(array);
else
mergeSort(array);为什么这里需要两种排序?为了提高效率?
发布于 2010-08-25 22:26:25
这是为了速度。mergeSort的开销足够高,对于短数组,它将比插入排序慢。
发布于 2010-08-25 22:59:23
引用自:http://en.wikipedia.org/wiki/Insertion_sort
Some divide-and-conquer algorithms such as quicksort and mergesort sort by
recursively dividing the list into smaller sublists which are then sorted.
A useful optimization in practice for these algorithms is to use insertion
sort for sorting small sublists, where insertion sort outperforms these more
complex algorithms. The size of list for which insertion sort has the advantage
varies by environment and implementation, but is typically between eight and
twenty elements.发布于 2010-08-25 22:26:58
似乎他们认为对于短数组,mergeSort(array)速度更慢。希望他们真的测试过了。
https://stackoverflow.com/questions/3566843
复制相似问题