1.问题:这三者中的sort排序有什么联系?
1.Collections.sort
public static <T extends Comparable<? super T>> void sort(List<T> list) {list.sort(null);}
2.Arrays.sort
/*** Sorts the specified array into ascending numerical order.** <p>Implementation note: The sorting algorithm is a Dual-Pivot Quicksort* by Vladimir Yaroslavskiy, Jon Bentley, and Joshua Bloch. This algorithm* offers O(n log(n)) performance on many data sets that cause other* quicksorts to degrade to quadratic performance, and is typically* faster than traditional (one-pivot) Quicksort implementations.** @param a the array to be sorted*/public static void sort(int[] a) {DualPivotQuicksort.sort(a, 0, a.length - 1, null, 0, 0);}
3.List.sort
default void sort(Comparator<? super E> c) {Object[] a = this.toArray();Arrays.sort(a, (Comparator) c);ListIterator<E> i = this.listIterator();for (Object e : a) {i.next();i.set((E) e);}}
所以不难看出,Collections.sort中的排序调用的就是List.sort中的默认方法,而List.sort中又调用了Arrays.sort
2.问题:Arrays.sort中做了什么?
可以看出,sort中有一个参数,是比较器。所以传入的对象必须要实现接口:Comparator或者new一个比较器
public static <T> void sort(T[] a, Comparator<? super T> c) {if (c == null) {sort(a);} else {if (LegacyMergeSort.userRequested)legacyMergeSort(a, c);elseTimSort.sort(a, 0, a.length, c, null, 0, 0);}}
2.1.如果比较器是null
public static void sort(Object[] a) {
if (LegacyMergeSort.userRequested)
legacyMergeSort(a);
else
ComparableTimSort.sort(a, 0, a.length, null, 0, 0);
}
2.1.A。如果用户要求,则使用归并排序(未来可能会被移除)
/** To be removed in a future release. */
private static void legacyMergeSort(Object[] a) {
Object[] aux = a.clone();
mergeSort(aux, a, 0, a.length, 0);
}
2.1.A.1.看需要排序的数组的长度是否小于“插入排序”的因子(默认为7),则直接使用插入排序
int length = high - low;
// Insertion sort on smallest arrays
if (length < INSERTIONSORT_THRESHOLD) {
for (int i=low; i<high; i++)
for (int j=i; j>low &&
((Comparable) dest[j-1]).compareTo(dest[j])>0; j--)
swap(dest, j, j-1);
return;
}
/**
* Tuning parameter: list size at or below which insertion sort will be
* used in preference to mergesort.
* To be removed in a future release.
*/
private static final int INSERTIONSORT_THRESHOLD = 7;
2.1.A.2.递归的将数组分为一半,直到满足使用插入排序为止
// Recursively sort halves of dest into src
int destLow = low;
int destHigh = high;
low += off;
high += off;
int mid = (low + high) >>> 1;
mergeSort(dest, src, low, mid, -off);
mergeSort(dest, src, mid, high, -off);
2.1.A.3.这时,已经把一个数组分为了排好序的两份,如果恰好中点的左边小于等于右边,恭喜你,发财了,这时数组已经排好序,直接返回即可
// If list is already sorted, just copy from src to dest. This is an
// optimization that results in faster sorts for nearly ordered lists.
if (((Comparable)src[mid-1]).compareTo(src[mid]) <= 0) {
System.arraycopy(src, low, dest, destLow, length);
return;
}
2.1.A.4.一般都不会这么巧,然后直接归并排序即可
// Merge sorted halves (now in src) into dest
for(int i = destLow, p = low, q = mid; i < destHigh; i++) {
if (q >= high || p < mid && ((Comparable)src[p]).compareTo(src[q])<=0)
dest[i] = src[p++];
else
dest[i] = src[q++];
}
2.1.B。如果用户没有要求,则使用时间排序
2.1.B.1.如果需要排序的数组长度小于等于2,则直接返回
int nRemaining = hi - lo;
if (nRemaining < 2)
2.1.B.2.这里jdk里又有一个判断,判断该排序的数组是不是属于小数组,如果是小数组,直接用迷你版的时间排序,而这个小的范围是32,小于该值就算
// If array is small, do a "mini-TimSort" with no merges
if (nRemaining < MIN_MERGE) {
int initRunLen = countRunAndMakeAscending(a, lo, hi);
binarySort(a, lo, hi, lo + initRunLen);
return;
}
2.1.B.3.方法“countRunAndMakeAscending”比较有意思了,先找出一段连续递增或递减的数组,如果递减则调换位置,总结就是找出从头开始的第一段连续递增(递减)的数据,最终是递增,并且返回这段连续的长度
int runHi = lo + 1;
if (runHi == hi)
return 1;
// Find end of run, and reverse range if descending
if (((Comparable) a[runHi++]).compareTo(a[lo]) < 0) { // Descending
while (runHi < hi && ((Comparable) a[runHi]).compareTo(a[runHi - 1]) < 0)
runHi++;
reverseRange(a, lo, runHi);
} else { // Ascending
while (runHi < hi && ((Comparable) a[runHi]).compareTo(a[runHi - 1]) >= 0)
runHi++;
}
return runHi - lo;
2.1.B.4.方法binarySort里面一看你就明白了
Comparable pivot = (Comparable) a[start];
// Set left (and right) to the index where a[start] (pivot) belongs
int left = lo;
int right = start;
assert left <= right;
/*
* Invariants:
* pivot >= all in [lo, left).
* pivot < all in [right, start).
*/
while (left < right) {
int mid = (left + right) >>> 1;
if (pivot.compareTo(a[mid]) < 0)
right = mid;
else
left = mid + 1;
}
其实在这个方法中,不难看出就是把第一个连续的递增数组后的数据以折中的方式去插入到他前面的数组汇中,应该说是找到其需要插入的位置。后面就是去循环的移动数组的位置,最终返回排好序的数组
/*
* The invariants still hold: pivot >= all in [lo, left) and
* pivot < all in [left, start), so pivot belongs at left. Note
* that if there are elements equal to pivot, left points to the
* first slot after them -- that's why this sort is stable.
* Slide elements over to make room for pivot.
*/
int n = start - left; // The number of elements to move
// Switch is just an optimization for arraycopy in default case
switch (n) {
case 2: a[left + 2] = a[left + 1];
case 1: a[left + 1] = a[left];
break;
default: System.arraycopy(a, left, a, left + 1, n);
}
a[left] = pivot;
2.1.C.1.如果数组的长度大于等于32,怎么办呢?我们继续解析源码
首先很有意思的一段源码,他的作用就是找出最小运行的长度,做一个解析
private static int minRunLength(int n) {
assert n >= 0;
int r = 0; // Becomes 1 if any 1 bits are shifted off
while (n >= MIN_MERGE) {
r |= (n & 1);
n >>= 1;
}
return n + r;
}
n<=16, return n; n>16, return 16 + n%16;
所以犹豫上面的32的范围已经阻止了小于16的可能性,总结:只要是2的n次幂,就返回16,如果不是,则返回16+其除以16的余数。为什么这么设计,后面会讲
int minRun = minRunLength(nRemaining);
do {
// Identify next run
int runLen = countRunAndMakeAscending(a, lo, hi);
// If run is short, extend to min(minRun, nRemaining)
if (runLen < minRun) {
int force = nRemaining <= minRun ? nRemaining : minRun;
binarySort(a, lo, lo + force, lo + runLen);
runLen = force;
}
// Push run onto pending-run stack, and maybe merge
ts.pushRun(lo, runLen);
ts.mergeCollapse();
// Advance to find next run
lo += runLen;
nRemaining -= runLen;
} while (nRemaining != 0);
哈哈,我们又看到了方法“countRunAndMakeAscending”,找出一段连续的数组,如果的递减的则倒叙,其实这种方法是前人经验得出的一个算法,有兴趣的大家可以搜一搜。
如果连续数组的长度小于最小执行长度,先找到数组长度与最小执行长度的最小值,然后将连续数组后的数组进行二叉排序,方法“binarySort”,具体解释上面有。
其实上面的代码就是先把数组分段,然后每段找出第一个连续的,在对其二叉排序,最终再合并这些分段排好序的数组。
2.2.如果比较器不为空,即自定义比较器,也分了是否有用户要求归并排序的需求
if (LegacyMergeSort.userRequested)
legacyMergeSort(a, c);
else
TimSort.sort(a, 0, a.length, c, null, 0, 0);
2.2.1.其实这个归并排序没啥可以讲得了,上面已经讲得已经很清楚了,直接跳过
2.2.2.最新的时间排序上面也讲过了,所以jdk的排序已经讲清楚了
