最近在刷算法题的过程中,频频用到Arrays.sort()这个排序API,所以我就想看一看这个方法的底层到底是采用什么排序策略。和我一起来看看吧!
// Use Quicksort on small arrays
if (right - left < QUICKSORT_THRESHOLD)
{
//QUICKSORT_THRESHOLD = 286
sort(a, left, right, true);
return;
}
数组一进来,会碰到第一个阀值:QUICKSORT_THRESHOLD(286),注解上说,小过这个阀值的进入Quicksort (快速排序),其实并不全是,点进去sort(a, left, right, true);方法:
// Use insertion sort on tiny arrays
if (length < INSERTION_SORT_THRESHOLD)
{
if (leftmost)
{
......
点进去后我们看到第二个阀值INSERTION_SORT_THRESHOLD(47),如果元素少于47这个阀值,就用插入排序,往下看确实如此:
/*
* Traditional (without sentinel) insertion sort,
* optimized for server VM, is used in case of
* the leftmost part.
*/
for (int i = left, j = i; i < right; j