classTimSort<T> { static <T> voidsort(T[] a, int lo, int hi, Comparator<? super T> c, T[] work, int workBase, int workLen) { assert c != null && a != null && lo >= 0 && lo <= hi && hi <= a.length;
intnRemaining= hi - lo; if (nRemaining < 2) return; // Arrays of size 0 and 1 are always sorted
// If array is small, do a "mini-TimSort" with no merges if (nRemaining < MIN_MERGE) { intinitRunLen= countRunAndMakeAscending(a, lo, hi, c); binarySort(a, lo, hi, lo + initRunLen, c); return; } ... } privatestatic <T> intcountRunAndMakeAscending(T[] a, int lo, int hi,Comparator<? super T> c) { assert lo < hi; intrunHi= lo + 1; if (runHi == hi) return1;
// Find end of run, and reverse range if descending if (c.compare(a[runHi++], a[lo]) < 0) { // Descending while (runHi < hi && c.compare(a[runHi], a[runHi - 1]) < 0) runHi++; reverseRange(a, lo, runHi); } else { // Ascending while (runHi < hi && c.compare(a[runHi], a[runHi - 1]) >= 0) runHi++; }