Untitled diff

Created Diff never expires
208 removals
Lines
Total
Removed
Words
Total
Removed
To continue using this feature, upgrade to
Diffchecker logo
Diffchecker Pro
673 lines
122 additions
Lines
Total
Added
Words
Total
Added
To continue using this feature, upgrade to
Diffchecker logo
Diffchecker Pro
680 lines
class TimSort<T> {
class Sorter<K, Buffer> {
/**
/**
* This is the minimum sized sequence that will be merged. Shorter
* This is the minimum sized sequence that will be merged. Shorter
* sequences will be lengthened by calling binarySort. If the entire
* sequences will be lengthened by calling binarySort. If the entire
* array is less than this length, no merges will be performed.
* array is less than this length, no merges will be performed.
*
*
* This constant should be a power of two. It was 64 in Tim Peter's C
* This constant should be a power of two. It was 64 in Tim Peter's C
* implementation, but 32 was empirically determined to work better in
* implementation, but 32 was empirically determined to work better in
* this implementation. In the unlikely event that you set this constant
* this implementation. In the unlikely event that you set this constant
* to be a number that's not a power of two, you'll need to change the
* to be a number that's not a power of two, you'll need to change the
* {@link #minRunLength} computation.
* minRunLength computation.
*
*
* If you decrease this constant, you must change the stackLen
* If you decrease this constant, you must change the stackLen
* computation in the TimSort constructor, or you risk an
* computation in the TimSort constructor, or you risk an
* ArrayOutOfBounds exception. See listsort.txt for a discussion
* ArrayOutOfBounds exception. See listsort.txt for a discussion
* of the minimum stack length required as a function of the length
* of the minimum stack length required as a function of the length
* of the array being sorted and the minimum merge sequence length.
* of the array being sorted and the minimum merge sequence length.
*/
*/
private static final int MIN_MERGE = 32;
private static final int MIN_MERGE = 32;
/*
private final SortDataFormat<K, Buffer> s;
* The next two methods (which are package private and static) constitute
* the entire API of this class. Each of these methods obeys the contract
* of the public method with the same signature in java.util.Arrays.
*/
static <T> void sort(T[] a, Comparator<? super T> c) {
public Sorter(SortDataFormat<K, Buffer> sortDataFormat) {
sort(a, 0, a.length, c);
this.s = sortDataFormat;
}
}
static <T> void sort(T[] a, int lo, int hi, Comparator<? super T> c) {
void sort(Buffer a, int lo, int hi, Comparator<? super K> c) {
if (c == null) {
assert c != null;
Arrays.sort(a, lo, hi);
return;
}
rangeCheck(a.length, lo, hi);
int nRemaining = hi - lo;
int nRemaining = hi - lo;
if (nRemaining < 2)
if (nRemaining < 2)
return; // Arrays of size 0 and 1 are always sorted
return; // Arrays of size 0 and 1 are always sorted
// If array is small, do a "mini-TimSort" with no merges
// If array is small, do a "mini-TimSort" with no merges
if (nRemaining < MIN_MERGE) {
if (nRemaining < MIN_MERGE) {
int initRunLen = countRunAndMakeAscending(a, lo, hi, c);
int initRunLen = countRunAndMakeAscending(a, lo, hi, c);
binarySort(a, lo, hi, lo + initRunLen, c);
binarySort(a, lo, hi, lo + initRunLen, c);
return;
return;
}
}
/**
/**
* March over the array once, left to right, finding natural runs,
* March over the array once, left to right, finding natural runs,
* extending short natural runs to minRun elements, and merging runs
* extending short natural runs to minRun elements, and merging runs
* to maintain stack invariant.
* to maintain stack invariant.
*/
*/
TimSort<T> ts = new TimSort<T>(a, c);
SortState sortState = new SortState(a, c, hi - lo);
int minRun = minRunLength(nRemaining);
int minRun = minRunLength(nRemaining);
do {
do {
// Identify next run
// Identify next run
int runLen = countRunAndMakeAscending(a, lo, hi, c);
int runLen = countRunAndMakeAscending(a, lo, hi, c);
// If run is short, extend to min(minRun, nRemaining)
// If run is short, extend to min(minRun, nRemaining)
if (runLen < minRun) {
if (runLen < minRun) {
int force = nRemaining <= minRun ? nRemaining : minRun;
int force = nRemaining <= minRun ? nRemaining : minRun;
binarySort(a, lo, lo + force, lo + runLen, c);
binarySort(a, lo, lo + force, lo + runLen, c);
runLen = force;
runLen = force;
}
}
// Push run onto pending-run stack, and maybe merge
// Push run onto pending-run stack, and maybe merge
ts.pushRun(lo, runLen);
sortState.pushRun(lo, runLen);
ts.mergeCollapse();
sortState.mergeCollapse();
// Advance to find next run
// Advance to find next run
lo += runLen;
lo += runLen;
nRemaining -= runLen;
nRemaining -= runLen;
} while (nRemaining != 0);
} while (nRemaining != 0);
// Merge all remaining runs to complete sort
// Merge all remaining runs to complete sort
assert lo == hi;
assert lo == hi;
ts.mergeForceCollapse();
sortState.mergeForceCollapse();
assert ts.stackSize == 1;
assert sortState.stackSize == 1;
}
}
/**
/**
* Sorts the specified portion of the specified array using a binary
* Sorts the specified portion of the specified array using a binary
* insertion sort. This is the best method for sorting small numbers
* insertion sort. This is the best method for sorting small numbers
* of elements. It requires O(n log n) compares, but O(n^2) data
* of elements. It requires O(n log n) compares, but O(n^2) data
* movement (worst case).
* movement (worst case).
*
*
* If the initial part of the specified range is already sorted,
* If the initial part of the specified range is already sorted,
* this method can take advantage of it: the method assumes that the
* this method can take advantage of it: the method assumes that the
* elements from index {@code lo}, inclusive, to {@code start},
* elements from index {@code lo}, inclusive, to {@code start},
* exclusive are already sorted.
* exclusive are already sorted.
*
*
* @param a the array in which a range is to be sorted
* @param a the array in which a range is to be sorted
* @param lo the index of the first element in the range to be sorted
* @param lo the index of the first element in the range to be sorted
* @param hi the index after the last element in the range to be sorted
* @param hi the index after the last element in the range to be sorted
* @param start the index of the first element in the range that is
* @param start the index of the first element in the range that is
* not already known to be sorted ({@code lo <= start <= hi})
* not already known to be sorted ({@code lo <= start <= hi})
* @param c comparator to used for the sort
* @param c comparator to used for the sort
*/
*/
@SuppressWarnings("fallthrough")
@SuppressWarnings("fallthrough")
private static <T> void binarySort(T[] a, int lo, int hi, int start,
private void binarySort(Buffer a, int lo, int hi, int start, Comparator<? super K> c) {
Comparator<? super T> c) {
assert lo <= start && start <= hi;
assert lo <= start && start <= hi;
if (start == lo)
if (start == lo)
start++;
start++;
for ( ; start < hi; start++) {
for ( ; start < hi; start++) {
T pivot = a[start];
Buffer pivotStore = s.allocate(1);
s.copyElement(a, start, pivotStore, 0);
K pivot = s.getKey(pivotStore, 0);
// Set left (and right) to the index where a[start] (pivot) belongs
// Set left (and right) to the index where a[start] (pivot) belongs
int left = lo;
int left = lo;
int right = start;
int right = start;
assert left <= right;
assert left <= right;
/*
/*
* Invariants:
* Invariants:
* pivot >= all in [lo, left).
* pivot >= all in [lo, left).
* pivot < all in [right, start).
* pivot < all in [right, start).
*/
*/
while (left < right) {
while (left < right) {
int mid = (left + right) >>> 1;
int mid = (left + right) >>> 1;
if (c.compare(pivot, a[mid]) < 0)
if (c.compare(pivot, s.getKey(a, mid)) < 0)
right = mid;
right = mid;
else
else
left = mid + 1;
left = mid + 1;
}
}
assert left == right;
assert left == right;
/*
/*
* The invariants still hold: pivot >= all in [lo, left) and
* The invariants still hold: pivot >= all in [lo, left) and
* pivot < all in [left, start), so pivot belongs at left. Note
* pivot < all in [left, start), so pivot belongs at left. Note
* that if there are elements equal to pivot, left points to the
* that if there are elements equal to pivot, left points to the
* first slot after them -- that's why this sort is stable.
* first slot after them -- that's why this sort is stable.
* Slide elements over to make room for pivot.
* Slide elements over to make room for pivot.
*/
*/
int n = start - left; // The number of elements to move
int n = start - left; // The number of elements to move
// Switch is just an optimization for arraycopy in default case
// Switch is just an optimization for arraycopy in default case
switch (n) {
switch (n) {
case 2: a[left + 2] = a[left + 1];
case 2: s.copyElement(a, left + 1, a, left + 2);
case 1: a[left + 1] = a[left];
case 1: s.copyElement(a, left, a, left + 1);
break;
break;
default: System.arraycopy(a, left, a, left + 1, n);
default: s.copyRange(a, left, a, left + 1, n);
}
}
a[left] = pivot;
s.copyElement(pivotStore, 0, a, left);
}
}
}
}
/**
/**
* Returns the length of the run beginning at the specified position in
* Returns the length of the run beginning at the specified position in
* the specified array and reverses the run if it is descending (ensuring
* the specified array and reverses the run if it is descending (ensuring
* that the run will always be ascending when the method returns).
* that the run will always be ascending when the method returns).
*
*
* A run is the longest ascending sequence with:
* A run is the longest ascending sequence with:
*
*
* a[lo] <= a[lo + 1] <= a[lo + 2] <= ...
* a[lo] <= a[lo + 1] <= a[lo + 2] <= ...
*
*
* or the longest descending sequence with:
* or the longest descending sequence with:
*
*
* a[lo] > a[lo + 1] > a[lo + 2] > ...
* a[lo] > a[lo + 1] > a[lo + 2] > ...
*
*
* For its intended use in a stable mergesort, the strictness of the
* For its intended use in a stable mergesort, the strictness of the
* definition of "descending" is needed so that the call can safely
* definition of "descending" is needed so that the call can safely
* reverse a descending sequence without violating stability.
* reverse a descending sequence without violating stability.
*
*
* @param a the array in which a run is to be counted and possibly reversed
* @param a the array in which a run is to be counted and possibly reversed
* @param lo index of the first element in the run
* @param lo index of the first element in the run
* @param hi index after the last element that may be contained in the run.
* @param hi index after the last element that may be contained in the run.
It is required that {@code lo < hi}.
It is required that {@code lo < hi}.
* @param c the comparator to used for the sort
* @param c the comparator to used for the sort
* @return the length of the run beginning at the specified position in
* @return the length of the run beginning at the specified position in
* the specified array
* the specified array
*/
*/
private static <T> int countRunAndMakeAscending(T[] a, int lo, int hi,
private int countRunAndMakeAscending(Buffer a, int lo, int hi, Comparator<? super K> c) {
Comparator<? super T> c) {
assert lo < hi;
assert lo < hi;
int runHi = lo + 1;
int runHi = lo + 1;
if (runHi == hi)
if (runHi == hi)
return 1;
return 1;
// Find end of run, and reverse range if descending
// Find end of run, and reverse range if descending
if (c.compare(a[runHi++], a[lo]) < 0) { // Descending
if (c.compare(s.getKey(a, runHi++), s.getKey(a, lo)) < 0) { // Descending
while (runHi < hi && c.compare(a[runHi], a[runHi - 1]) < 0)
while (runHi < hi && c.compare(s.getKey(a, runHi), s.getKey(a, runHi - 1)) < 0)
runHi++;
runHi++;
reverseRange(a, lo, runHi);
reverseRange(a, lo, runHi);
} else { // Ascending
} else { // Ascending
while (runHi < hi && c.compare(a[runHi], a[runHi - 1]) >= 0)
while (runHi < hi && c.compare(s.getKey(a, runHi), s.getKey(a, runHi - 1)) >= 0)
runHi++;
runHi++;
}
}
return runHi - lo;
return runHi - lo;
}
}
/**
/**
* Reverse the specified range of the specified array.
* Reverse the specified range of the specified array.
*
*
* @param a the array in which a range is to be reversed
* @param a the array in which a range is to be reversed
* @param lo the index of the first element in the range to be reversed
* @param lo the index of the first element in the range to be reversed
* @param hi the index after the last element in the range to be reversed
* @param hi the index after the last element in the range to be reversed
*/
*/
private static void reverseRange(Object[] a, int lo, int hi) {
private void reverseRange(Buffer a, int lo, int hi) {
hi--;
hi--;
while (lo < hi) {
while (lo < hi) {
Object t = a[lo];
s.swap(a, lo, hi);
a[lo++] = a[hi];
lo++;
a[hi--] = t;
hi--;
}
}
}
}
/**
/**
* Returns the minimum acceptable run length for an array of the specified
* Returns the minimum acceptable run length for an array of the specified
* length. Natural runs shorter than this will be extended with
* length. Natural runs shorter than this will be extended with
* {@link #binarySort}.
* {@link #binarySort}.
*
*
* Roughly speaking, the computation is:
* Roughly speaking, the computation is:
*
*
* If n < MIN_MERGE, return n (it's too small to bother with fancy stuff).
* If n < MIN_MERGE, return n (it's too small to bother with fancy stuff).
* Else if n is an exact power of 2, return MIN_MERGE/2.
* Else if n is an exact power of 2, return MIN_MERGE/2.
* Else return an int k, MIN_MERGE/2 <= k <= MIN_MERGE, such that n/k
* Else return an int k, MIN_MERGE/2 <= k <= MIN_MERGE, such that n/k
* is close to, but strictly less than, an exact power of 2.
* is close to, but strictly less than, an exact power of 2.
*
*
* For the rationale, see listsort.txt.
* For the rationale, see listsort.txt.
*
*
* @param n the length of the array to be sorted
* @param n the length of the array to be sorted
* @return the length of the minimum run to be merged
* @return the length of the minimum run to be merged
*/
*/
private static int minRunLength(int n) {
private int minRunLength(int n) {
assert n >= 0;
assert n >= 0;
int r = 0; // Becomes 1 if any 1 bits are shifted off
int r = 0; // Becomes 1 if any 1 bits are shifted off
while (n >= MIN_MERGE) {
while (n >= MIN_MERGE) {
r |= (n & 1);
r |= (n & 1);
n >>= 1;
n >>= 1;
}
}
return n + r;
return n + r;
}
}
private class SortState {
/**
/**
* The array being sorted.
* The Buffer being sorted.
*/
*/
private final T[] a;
private final Buffer a;
/**
* Length of the sort Buffer.
*/
private final int aLength;
/**
/**
* The comparator for this sort.
* The comparator for this sort.
*/
*/
private final Comparator<? super T> c;
private final Comparator<? super K> c;
/**
/**
* When we get into galloping mode, we stay there until both runs win less
* When we get into galloping mode, we stay there until both runs win less
* often than MIN_GALLOP consecutive times.
* often than MIN_GALLOP consecutive times.
*/
*/
private static final int MIN_GALLOP = 7;
private static final int MIN_GALLOP = 7;
/**
/**
* This controls when we get *into* galloping mode. It is initialized
* This controls when we get *into* galloping mode. It is initialized
* to MIN_GALLOP. The mergeLo and mergeHi methods nudge it higher for
* to MIN_GALLOP. The mergeLo and mergeHi methods nudge it higher for
* random data, and lower for highly structured data.
* random data, and lower for highly structured data.
*/
*/
private int minGallop = MIN_GALLOP;
private int minGallop = MIN_GALLOP;
/**
/**
* Maximum initial size of tmp array, which is used for merging. The array
* Maximum initial size of tmp array, which is used for merging. The array
* can grow to accommodate demand.
* can grow to accommodate demand.
*
*
* Unlike Tim's original C version, we do not allocate this much storage
* Unlike Tim's original C version, we do not allocate this much storage
* when sorting smaller arrays. This change was required for performance.
* when sorting smaller arrays. This change was required for performance.
*/
*/
private static final int INITIAL_TMP_STORAGE_LENGTH = 256;
private static final int INITIAL_TMP_STORAGE_LENGTH = 256;
/**
/**
* Temp storage for merges.
* Temp storage for merges.
*/
*/
private T[] tmp; // Actual runtime type will be Object[], regardless of T
private Buffer tmp; // Actual runtime type will be Object[], regardless of T
/**
* Length of the temp storage.
*/
private int tmpLength = 0;
/**
/**
* A stack of pending runs yet to be merged. Run i starts at
* A stack of pending runs yet to be merged. Run i starts at
* address base[i] and extends for len[i] elements. It's always
* address base[i] and extends for len[i] elements. It's always
* true (so long as the indices are in bounds) that:
* true (so long as the indices are in bounds) that:
*
*
* runBase[i] + runLen[i] == runBase[i + 1]
* runBase[i] + runLen[i] == runBase[i + 1]
*
*
* so we could cut the storage for this, but it's a minor amount,
* so we could cut the storage for this, but it's a minor amount,
* and keeping all the info explicit simplifies the code.
* and keeping all the info explicit simplifies the code.
*/
*/
private int stackSize = 0; // Number of pending runs on stack
private int stackSize = 0; // Number of pending runs on stack
private final int[] runBase;
private final int[] runBase;
private final int[] runLen;
private final int[] runLen;
/**
/**
* Creates a TimSort instance to maintain the state of an ongoing sort.
* Creates a TimSort instance to maintain the state of an ongoing sort.
*
*
* @param a the array to be sorted
* @param a the array to be sorted
* @param c the comparator to determine the order of the sort
* @param c the comparator to determine the order of the sort
*/
*/
private TimSort(T[] a, Comparator<? super T> c) {
private SortState(Buffer a, Comparator<? super K> c, int len) {
this.aLength = len;
this.a = a;
this.a = a;
this.c = c;
this.c = c;
// Allocate temp storage (which may be increased later if necessary)
// Allocate temp storage (which may be increased later if necessary)
int len = a.length;
tmpLength = len < 2 * INITIAL_TMP_STORAGE_LENGTH ? len >>> 1 : INITIAL_TMP_STORAGE_LENGTH;
@SuppressWarnings({"unchecked", "UnnecessaryLocalVariable"})
tmp = s.allocate(tmpLength);
T[] newArray = (T[]) new Object[len < 2 * INITIAL_TMP_STORAGE_LENGTH ?
len >>> 1 : INITIAL_TMP_STORAGE_LENGTH];
/*
tmp = newArray;
* Allocate runs-to-be-merged stack (which cannot be expanded). The
* stack length requirements are described in listsort.txt. The C
/*
* version always uses the same stack length (85), but this was
* Allocate runs-to-be-merged stack (which cannot be expanded). The
* measured to be too expensive when sorting "mid-sized" arrays (e.g.,
* stack length requirements are described in listsort.txt. The C
* 100 elements) in Java. Therefore, we use smaller (but sufficiently
* version always uses the same stack length (85), but this was
* large) stack lengths for smaller arrays. The "magic numbers" in the
* measured to be too expensive when sorting "mid-sized" arrays (e.g.,
* computation below must be changed if MIN_MERGE is decreased. See
* 100 elements) in Java. Therefore, we use smaller (but sufficiently
* the MIN_MERGE declaration above for more information.
* large) stack lengths for smaller arrays. The "magic numbers" in the
*/
* computation below must be changed if MIN_MERGE is decreased. See
* the MIN_MERGE declaration above for more information.
*/
int stackLen = (len < 120 ? 5 :
int stackLen = (len < 120 ? 5 :
len < 1542 ? 10 :
len < 1542 ? 10 :
len < 119151 ? 19 : 40);
len < 119151 ? 19 : 40);
runBase = new int[stackLen];
runBase = new int[stackLen];
runLen = new int[stackLen];
runLen = new int[stackLen];
}
}
/**
/**
* Pushes the specified run onto the pending-run stack.
* Pushes the specified run onto the pending-run stack.
*
*
* @param runBase index of the first element in the run
* @param runBase index of the first element in the run
* @param runLen the number of elements in the run
* @param runLen the number of elements in the run
*/
*/
private void pushRun(int runBase, int runLen) {
private void pushRun(int runBase, int runLen) {
this.runBase[stackSize] = runBase;
this.runBase[stackSize] = runBase;
this.runLen[stackSize] = runLen;
this.runLen[stackSize] = runLen;
stackSize++;
stackSize++;
}
}
/**
/**
* Examines the stack of runs waiting to be merged and merges adjacent runs
* Examines the stack of runs waiting to be merged and merges adjacent runs
* until the stack invariants are reestablished:
* until the stack invariants are reestablished:
*
*
* 1. runLen[i - 3] > runLen[i - 2] + runLen[i - 1]
* 1. runLen[i - 3] > runLen[i - 2] + runLen[i - 1]
* 2. runLen[i - 2] > runLen[i - 1]
* 2. runLen[i - 2] > runLen[i - 1]
*
*
* This method is called each time a new run is pushed onto the stack,
* This method is called each time a new run is pushed onto the stack,
* so the invariants are guaranteed to hold for i < stackSize upon
* so the invariants are guaranteed to hold for i < stackSize upon
* entry to the method.
* entry to the method.
*/
*/
private void mergeCollapse() {
private void mergeCollapse() {
while (stackSize > 1) {
while (stackSize > 1) {
int n = stackSize - 2;
int n = stackSize - 2;
if (n > 0 && runLen[n-1] <= runLen[n] + runLen[n+1]) {
if (n > 0 && runLen[n-1] <= runLen[n] + runLen[n+1]) {
if (runLen[n - 1] < runLen[n + 1])
if (runLen[n - 1] < runLen[n + 1])
n--;
n--;
mergeAt(n);
mergeAt(n);
} else if (runLen[n] <= runLen[n + 1]) {
} else if (runLen[n] <= runLen[n + 1]) {
mergeAt(n);
mergeAt(n);
} else {
} else {
break; // Invariant is established
break; // Invariant is established
}
}
}
}
}
}
/**
/**
* Merges all runs on the stack until only one remains. This method is
* Merges all runs on the stack until only one remains. This method is
* called once, to complete the sort.
* called once, to complete the sort.
*/
*/
private void mergeForceCollapse() {
private void mergeForceCollapse() {
while (stackSize > 1) {
while (stackSize > 1) {
int n = stackSize - 2;
int n = stackSize - 2;
if (n > 0 && runLen[n - 1] < runLen[n + 1])
if (n > 0 && runLen[n - 1] < runLen[n + 1])
n--;
n--;
mergeAt(n);
mergeAt(n);
}
}
}
}
/**
/**
* Merges the two runs at stack indices i and i+1. Run i must be
* Merges the two runs at stack indices i and i+1. Run i must be
* the penultimate or antepenultimate run on the stack. In other words,
* the penultimate or antepenultimate run on the stack. In other words,
* i must be equal to stackSize-2 or stackSize-3.
* i must be equal to stackSize-2 or stackSize-3.
*
*
* @param i stack index of the first of the two runs to merge
* @param i stack index of the first of the two runs to merge
*/
*/
private void mergeAt(int i) {
private void mergeAt(int i) {
assert stackSize >= 2;
assert stackSize >= 2;
assert i >= 0;
assert i >= 0;
assert i == stackSize - 2 || i == stackSize - 3;
assert i == stackSize - 2 || i == stackSize - 3;
int base1 = runBase[i];
int base1 = runBase[i];
int len1 = runLen[i];
int len1 = runLen[i];
int base2 = runBase[i + 1];
int base2 = runBase[i + 1];
int len2 = runLen[i + 1];
int len2 = runLen[i + 1];
assert len1 > 0 && len2 > 0;
assert len1 > 0 && len2 > 0;
assert base1 + len1 == base2;
assert base1 + len1 == base2;
/*
/*
* Record the length of the combined runs; if i is the 3rd-last
* Record the length of the combined runs; if i is the 3rd-last
* run now, also slide over the last run (which isn't involved
* run now, also slide over the last run (which isn't involved
* in this merge). The current run (i+1) goes away in any case.
* in this merge). The current run (i+1) goes away in any case.
*/
*/
runLen[i] = len1 + len2;
runLen[i] = len1 + len2;
if (i == stackSize - 3) {
if (i == stackSize - 3) {
runBase[i + 1] = runBase[i + 2];
runBase[i + 1] = runBase[i + 2];
runLen[i + 1] = runLen[i + 2];
runLen[i + 1] = runLen[i + 2];
}
}
stackSize--;
stackSize--;
/*
/*
* Find where the first element of run2 goes in run1. Prior elements
* Find where the first element of run2 goes in run1. Prior elements
* in run1 can be ignored (because they're already in place).
* in run1 can be ignored (because they're already in place).
*/
*/
int k = gallopRight(a[base2], a, base1, len1, 0, c);
int k = gallopRight(s.getKey(a, base2), a, base1, len1, 0, c);
assert k >= 0;
assert k >= 0;
base1 += k;
base1 += k;
len1 -= k;
len1 -= k;
if (len1 == 0)
if (len1 == 0)
return;
return;
/*
/*
* Find where the last element of run1 goes in run2. Subsequent elements
* Find where the last element of run1 goes in run2. Subsequent elements
* in run2 can be ignored (because they're already in place).
* in run2 can be ignored (because they're already in place).
*/
*/
len2 = gallopLeft(a[base1 + len1 - 1], a, base2, len2, len2 - 1, c);
len2 = gallopLeft(s.getKey(a, base1 + len1 - 1), a, base2, len2, len2 - 1, c);
assert len2 >= 0;
assert len2 >= 0;
if (len2 == 0)
if (len2 == 0)
return;
return;
// Merge remaining runs, using tmp array with min(len1, len2) elements
// Merge remaining runs, using tmp array with min(len1, len2) elements
if (len1 <= len2)
if (len1 <= len2)
mergeLo(base1, len1, base2, len2);
mergeLo(base1, len1, base2, len2);
else
else
mergeHi(base1, len1, base2, len2);
mergeHi(base1, len1, base2, len2);
}
}
/**
/**
* Locates the position at which to insert the specified key into the
* Locates the position at which to insert the specified key into the
* specified sorted range; if the range contains an element equal to key,
* specified sorted range; if the range contains an element equal to key,
* returns the index of the leftmost equal element.
* returns the index of the leftmost equal element.
*
*
* @param key the key whose insertion point to search for
* @param key the key whose insertion point to search for
* @param a the array in which to search
* @param a the array in which to search
* @param base the index of the first element in the range
* @param base the index of the first element in the range
* @param len the length of the range; must be > 0
* @param len the length of the range; must be > 0
* @param hint the index at which to begin the search, 0 <= hint < n.
* @param hint the index at which to begin the search, 0 <= hint < n.
* The closer hint is to the result, the faster this method will run.
* The closer hint is to the result, the faster this method will run.
* @param c the comparator used to order the range, and to search
* @param c the comparator used to order the range, and to search
* @return the int k, 0 <= k <= n such that a[b + k - 1] < key <= a[b + k],
* @return the int k, 0 <= k <= n such that a[b + k - 1] < key <= a[b + k],
* pretending that a[b - 1] is minus infinity and a[b + n] is infinity.
* pretending that a[b - 1] is minus infinity and a[b + n] is infinity.
* In other words, key belongs at index b + k; or in other words,
* In other words, key belongs at index b + k; or in other words,
* the first k elements of a should precede key, and the last n - k
* the first k elements of a should precede key, and the last n - k
* should follow it.
* should follow it.
*/
*/
private static <T> int gallopLeft(T key, T[] a, int base, int len, int hint,
private int gallopLeft(K key, Buffer a, int base, int len, int hint, Comparator<? super K> c) {
Comparator<? super T> c) {
assert len > 0 && hint >= 0 && hint < len;
assert len > 0 && hint >= 0 && hint < len;
int lastOfs = 0;
int lastOfs = 0;
int ofs = 1;
int ofs = 1;
if (c.compare(key, a[base + hint]) > 0) {
if (c.compare(key, s.getKey(a, base + hint)) > 0) {
// Gallop right until a[base+hint+lastOfs] < key <= a[base+hint+ofs]
// Gallop right until a[base+hint+lastOfs] < key <= a[base+hint+ofs]
int maxOfs = len - hint;
int maxOfs = len - hint;
while (ofs < maxOfs && c.compare(key, a[base + hint + ofs]) > 0) {
while (ofs < maxOfs && c.compare(key, s.getKey(a, base + hint + ofs)) > 0) {
lastOfs = ofs;
lastOfs = ofs;
ofs = (ofs << 1) + 1;
ofs = (ofs << 1) + 1;
if (ofs <= 0) // int overflow
if (ofs <= 0) // int overflow
ofs = maxOfs;
ofs = maxOfs;
}
}
if (ofs > maxOfs)
if (ofs > maxOfs)
ofs = maxOfs;
ofs = maxOfs;
// Make offsets relative to base
// Make offsets relative to base
lastOfs += hint;
lastOfs += hint;
ofs += hint;
ofs += hint;
} else { // key <= a[base + hint]
} else { // key <= a[base + hint]
// Gallop left until a[base+hint-ofs] < key <= a[base+hint-lastOfs]
// Gallop left until a[base+hint-ofs] < key <= a[base+hint-lastOfs]
final int maxOfs = hint + 1;
final int maxOfs = hint + 1;
while (ofs < maxOfs && c.compare(key, a[base + hint - ofs]) <= 0) {
while (ofs < maxOfs && c.compare(key, s.getKey(a, base + hint - ofs)) <= 0) {
lastOfs = ofs;
lastOfs = ofs;
ofs = (ofs << 1) + 1;
ofs = (ofs << 1) + 1;
if (ofs <= 0) // int overflow
if (ofs <= 0) // int overflow
ofs = maxOfs;
ofs = maxOfs;
}
}
if (ofs > maxOfs)
if (ofs > maxOfs)
ofs = maxOfs;
ofs = maxOfs;
// Make offsets relative to base
// Make offsets relative to base
int tmp = lastOfs;
int tmp = lastOfs;
lastOfs = hint - ofs;
lastOfs = hint - ofs;
ofs = hint - tmp;
ofs = hint - tmp;
}
}
assert -1 <= lastOfs && lastOfs < ofs && ofs <= len;
assert -1 <= lastOfs && lastOfs < ofs && ofs <= len;
/*
/*
* Now a[base+lastOfs] < key <= a[base+ofs], so key belongs somewhere
* Now a[base+lastOfs] < key <= a[base+ofs], so key belongs somewhere
* to the right of lastOfs but no farther right than ofs. Do a binary
* to the right of lastOfs but no farther right than ofs. Do a binary
* search, with invariant a[base + lastOfs - 1] < key <= a[base + ofs].
* search, with invariant a[base + lastOfs - 1] < key <= a[base + ofs].
*/
*/
lastOfs++;
lastOfs++;
while (lastOfs < ofs) {
while (lastOfs < ofs) {
int m = lastOfs + ((ofs - lastOfs) >>> 1);
int m = lastOfs + ((ofs - lastOfs) >>> 1);
if (c.compare(key, a[base + m]) > 0)
if (c.compare(key, s.getKey(a, base + m)) > 0)
lastOfs = m + 1; // a[base + m] < key
lastOfs = m + 1; // a[base + m] < key
else
else
ofs = m; // key <= a[base + m]
ofs = m; // key <= a[base + m]
}
}
assert lastOfs == ofs; // so a[base + ofs - 1] < key <= a[base + ofs]
assert lastOfs == ofs; // so a[base + ofs - 1] < key <= a[base + ofs]
return ofs;
return ofs;
}
}
/**
/**
* Like gallopLeft, except that if the range contains an element equal to
* Like gallopLeft, except that if the range contains an element equal to
* key, gallopRight returns the index after the rightmost equal element.
* key, gallopRight returns the index after the rightmost equal element.
*
*
* @param key the key whose insertion point to search for
* @param key the key whose insertion point to search for
* @param a the array in which to search
* @param a the array in which to search
* @param base the index of the first element in the range
* @param base the index of the first element in the range
* @param len the length of the range; must be > 0
* @param len the length of the range; must be > 0
* @param hint the index at which to begin the search, 0 <= hint < n.
* @param hint the index at which to begin the search, 0 <= hint < n.
* The closer hint is to the result, the faster this method will run.
* The closer hint is to the result, the faster this method will run.
* @param c the comparator used to order the range, and to search
* @param c the comparator used to order the range, and to search
* @return the int k, 0 <= k <= n such that a[b + k - 1] <= key < a[b + k]
* @return the int k, 0 <= k <= n such that a[b + k - 1] <= key < a[b + k]
*/
*/
private static <T> int gallopRight(T key, T[] a, int base, int len,
private int gallopRight(K key, Buffer a, int base, int len, int hint, Comparator<? super K> c) {
int hint, Comparator<? super T> c) {
assert len > 0 && hint >= 0 && hint < len;
assert len > 0 && hint >= 0 && hint < len;
int ofs = 1;
int ofs = 1;
int lastOfs = 0;
int lastOfs = 0;
if (c.compare(key, a[base + hint]) < 0) {
if (c.compare(key, s.getKey(a, base + hint)) < 0) {
// Gallop left until a[b+hint - ofs] <= key < a[b+hint - lastOfs]
// Gallop left until a[b+hint - ofs] <= key < a[b+hint - lastOfs]
int maxOfs = hint + 1;
int maxOfs = hint + 1;
while (ofs < maxOfs && c.compare(key, a[base + hint - ofs]) < 0) {
while (ofs < maxOfs && c.compare(key, s.getKey(a, base + hint - ofs)) < 0) {
lastOfs = ofs;
lastOfs = ofs;
ofs = (ofs << 1) + 1;
ofs = (ofs << 1) + 1;
if (ofs <= 0) // int overflow
if (ofs <= 0) // int overflow
ofs = maxOfs;
ofs = maxOfs;
}
}
if (ofs > maxOfs)
if (ofs > maxOfs)
ofs = maxOfs;
ofs = maxOfs;
// Make offsets relative to b
// Make offsets relative to b
int tmp = lastOfs;
int tmp = lastOfs;
lastOfs = hint - ofs;
lastOfs = hint - ofs;
ofs = hint - tmp;
ofs = hint - tmp;
} else { // a[b + hint] <= key
} else { // a[b + hint] <= key
// Gallop right until a[b+hint + lastOfs] <= key < a[b+hint + ofs]
// Gallop right until a[b+hint + lastOfs] <= key < a[b+hint + ofs]
int maxOfs = len - hint;
int maxOfs = len - hint;
while (ofs < maxOfs && c.compare(key, a[base + hint + ofs]) >= 0) {
while (ofs < maxOfs && c.compare(key, s.getKey(a, base + hint + ofs)) >= 0) {
lastOfs = ofs;
lastOfs = ofs;
ofs = (ofs << 1) + 1;
ofs = (ofs << 1) + 1;
if (ofs <= 0) // int overflow
if (ofs <= 0) // int overflow
ofs = maxOfs;
ofs = maxOfs;
}
}
if (ofs > maxOfs)
if (ofs > maxOfs)
ofs = maxOfs;
ofs = maxOfs;
// Make offsets relative to b
// Make offsets relative to b
lastOfs += hint;
lastOfs += hint;
ofs += hint;
ofs += hint;
}
}
assert -1 <= lastOfs && lastOfs < ofs && ofs <= len;
assert -1 <= lastOfs && lastOfs < ofs && ofs <= len;
/*
/*
* Now a[b + lastOfs] <= key < a[b + ofs], so key belongs somewhere to
* Now a[b + lastOfs] <= key < a[b + ofs], so key belongs somewhere to
* the right of lastOfs but no farther right than ofs. Do a binary
* the right of lastOfs but no farther right than ofs. Do a binary
* search, with invariant a[b + lastOfs - 1] <= key < a[b + ofs].
* search, with invariant a[b + lastOfs - 1] <= key < a[b + ofs].
*/
*/
lastOfs++;
lastOfs++;
while (lastOfs < ofs) {
while (lastOfs < ofs) {
int m = lastOfs + ((ofs - lastOfs) >>> 1);
int m = lastOfs + ((ofs - lastOfs) >>> 1);
if (c.compare(key, a[base + m]) < 0)
if (c.compare(key, s.getKey(a, base + m)) < 0)
ofs = m; // key < a[b + m]
ofs = m; // key < a[b + m]
else
else
lastOfs = m + 1; // a[b + m] <= key
lastOfs = m + 1; // a[b + m] <= key
}
}
assert lastOfs == ofs; // so a[b + ofs - 1] <= key < a[b + ofs]
assert lastOfs == ofs; // so a[b + ofs - 1] <= key < a[b + ofs]
return ofs;
return ofs;
}
}
/**
/**
* Merges two adjacent runs in place, in a stable fashion. The first
* Merges two adjacent runs in place, in a stable fashion. The first
* element of the first run must be greater than the first element of the
* element of the first run must be greater than the first element of the
* second run (a[base1] > a[base2]), and the last element of the first run
* second run (a[base1] > a[base2]), and the last element of the first run
* (a[base1 + len1-1]) must be greater than all elements of the second run.
* (a[base1 + len1-1]) must be greater than all elements of the second run.
*
*
* For performance, this method should be called only when len1 <= len2;
* For performance, this method should be called only when len1 <= len2;
* its twin, mergeHi should be called if len1 >= len2. (Either method
* its twin, mergeHi should be called if len1 >= len2. (Either method
* may be called if len1 == len2.)
* may be called if len1 == len2.)
*
*
* @param base1 index of first element in first run to be merged
* @param base1 index of first element in first run to be merged
* @param len1 length of first run to be merged (must be > 0)
* @param len1 length of first run to be merged (must be > 0)
* @param base2 index of first element in second run to be merged
* @param base2 index of first element in second run to be merged
* (must be aBase + aLen)
* (must be aBase + aLen)
* @param len2 length of second run to be merged (must be > 0)
* @param len2 length of second run to be merged (must be > 0)
*/
*/
private void mergeLo(int base1, int len1, int base2, int len2) {
private void mergeLo(int base1, int len1, int base2, int len2) {
assert len1 > 0 && len2 > 0 && base1 + len1 == base2;
assert len1 > 0 && len2 > 0 && base1 + len1 == base2;
// Copy first run into temp array
// Copy first run into temp array
T[] a = this.a; // For performance
Buffer a = this.a; // For performance
T[] tmp = ensureCapacity(len1);
Buffer tmp = ensureCapacity(len1);
System.arraycopy(a, base1, tmp, 0, len1);
s.copyRange(a, base1, tmp, 0, len1);
int cursor1 = 0; // Indexes into tmp array
int cursor1 = 0; // Indexes into tmp array
int cursor2 = base2; // Indexes int a
int cursor2 = base2; // Indexes int a
int dest = base1; // Indexes int a
int dest = base1; // Indexes int a
// Move first element of second run and deal with degenerate cases
// Move first element of second run and deal with degenerate cases
a[dest++] = a[cursor2++];
s.copyElement(a, cursor2++, a, dest++);
if (--len2 == 0) {
if (--len2 == 0) {
System.arraycopy(tmp, cursor1, a, dest, len1);
s.copyRange(tmp, cursor1, a, dest, len1);
return;
return;
}
}
if (len1 == 1) {
if (len1 == 1) {
System.arraycopy(a, cursor2, a, dest, len2);
s.copyRange(a, cursor2, a, dest, len2);
a[dest + len2] = tmp[cursor1]; // Last elt of run 1 to end of merge
s.copyElement(tmp, cursor1, a, dest + len2); // Last elt of run 1 to end of merge
return;
return;
}
}
Comparator<? super T> c = this.c; // Use local variable for performance
Comparator<? super K> c = this.c; // Use local variable for performance
int minGallop = this.minGallop; // " " " " "
int minGallop = this.minGallop; // " " " " "
outer:
outer:
while (true) {
while (true) {
int count1 = 0; // Number of times in a row that first run won
int count1 = 0; // Number of times in a row that first run won
int count2 = 0; // Number of times in a row that second run won
int count2 = 0; // Number of times in a row that second run won
/*
/*
* Do the straightforward thing until (if ever) one run starts
* Do the straightforward thing until (if ever) one run starts
* winning consistently.
* winning consistently.
*/
*/
do {
do {
assert len1 > 1 && len2 > 0;
assert len1 > 1 && len2 > 0;
if (c.compare(a[cursor2], tmp[cursor1]) < 0) {
if (c.compare(s.getKey(a, cursor2), s.getKey(tmp, cursor1)) < 0) {
a[dest++] = a[cursor2++];
s.copyElement(a, cursor2++, a, dest++);
count2++;
count2++;
count1 = 0;
count1 = 0;
if (--len2 == 0)
if (--len2 == 0)
break outer;
break outer;
} else {
} else {
a[dest++] = tmp[cursor1++];
s.copyElement(tmp, cursor1++, a, dest++);
count1++;
count1++;
count2 = 0;
count2 = 0;
if (--len1 == 1)
if (--len1 == 1)
break outer;
break outer;
}
}
} while ((count1 | count2) < minGallop);
} while ((count1 | count2) < minGallop);
/*
/*
* One run is winning so consistently that galloping may be a
* One run is winning so consistently that galloping may be a
* huge win. So try that, and continue galloping until (if ever)
* huge win. So try that, and continue galloping until (if ever)
* neither run appears to be winning consistently anymore.
* neither run appears to be winning consistently anymore.
*/
*/
do {
do {
assert len1 > 1 && len2 > 0;
assert len1 > 1 && len2 > 0;
count1 = gallopRight(a[cursor2], tmp, cursor1, len1, 0, c);
count1 = gallopRight(s.getKey(a, cursor2), tmp, cursor1, len1, 0, c);
if (count1 != 0) {
if (count1 != 0) {
System.arraycopy(tmp, cursor1, a, dest, count1);
s.copyRange(tmp, cursor1, a, dest, count1);
dest += count1;
dest += count1;
cursor1 += count1;
cursor1 += count1;
len1 -= count1;
len1 -= count1;
if (len1 <= 1) // len1 == 1 || len1 == 0
if (len1 <= 1) // len1 == 1 || len1 == 0
break outer;
break outer;
}
}
a[dest++] = a[cursor2++];
s.copyElement(a, cursor2++, a, dest++);
if (--len2 == 0)
if (--len2 == 0)
break outer;
break outer;
count2 = gallopLeft(tmp[cursor1], a, cursor2, len2, 0, c);
count2 = gallopLeft(s.getKey(tmp, cursor1), a, cursor2, len2, 0, c);
if (count2 != 0) {
if (count2 != 0) {
System.arraycopy(a, cursor2, a, dest, count2);
s.copyRange(a, cursor2, a, dest, count2);
dest += count2;
dest += count2;
cursor2 += count2;
cursor2 += count2;
len2 -= count2;
len2 -= count2;
if (len2 == 0)
if (len2 == 0)
break outer;
break outer;
}
}
a[dest++] = tmp[cursor1++];
s.copyElement(tmp, cursor1++, a, dest++);
if (--len1 == 1)
if (--len1 == 1)
break outer;
minGallop--;
} while (count1 >= MIN_GALLOP | count2 >= MIN_GALLOP);
if (minGallop < 0)
minGallop = 0;
minGallop += 2; // Penalize for leaving gallop mode
} // End