APIdia Launch Partner
Top Description Fields Constructors Methods
com.badlogic.gdx.utils

pack-priv Class ComparableTimSort

extends Object
Class Inheritance
Imports
java.util.Arrays

This is a near duplicate of TimSort, modified for use with arrays of objects that implement Comparable, instead of using explicit comparators.

If you are using an optimizing VM, you may find that ComparableTimSort offers no performance benefit over TimSort in conjunction with a comparator that simply returns ((Comparable)first).compareTo(Second). If this is the case, you are better off deleting ComparableTimSort to eliminate the code duplication. (See Arrays.java for details.)

Field Summary

Modifier and TypeField and Description
private Object[]
a

The array being sorted.

private static final boolean
DEBUG

Asserts have been placed in if-statements for performace.

private static final int
INITIAL_TMP_STORAGE_LENGTH

Maximum initial size of tmp array, which is used for merging.

private static final int
MIN_GALLOP

When we get into galloping mode, we stay there until both runs win less often than MIN_GALLOP consecutive times.

private static final int
MIN_MERGE

This is the minimum sized sequence that will be merged.

private int
minGallop

This controls when we get *into* galloping mode.

private final int[]
private final int[]
private int
stackSize

A stack of pending runs yet to be merged.

private Object[]
tmp

Temp storage for merges.

private int

Constructor Summary

AccessConstructor and Description
pack-priv
private
ComparableTimSort(Object[]
the array to be sorted
a
)

Creates a TimSort instance to maintain the state of an ongoing sort.

Method Summary

Modifier and TypeMethod and Description
private static void
binarySort(Object[]
the array in which a range is to be sorted
a
,
int
the index of the first element in the range to be sorted
lo
,
int
the index after the last element in the range to be sorted
hi
,
int
the index of the first element in the range that is not already known to be sorted (@code lo <= start <= hi}
start
)

Sorts the specified portion of the specified array using a binary insertion sort.

private static int

Returns:

the length of the run beginning at the specified position in the specified array
countRunAndMakeAscending
(Object[]
the array in which a run is to be counted and possibly reversed
a
,
int
index of the first element in the run
lo
,
int
index after the last element that may be contained in the run. It is required that @code{lo < hi}.
hi
)

Returns the length of the run beginning at the specified position in the specified array and reverses the run if it is descending (ensuring that the run will always be ascending when the method returns).

public void
doSort(Object[] a, int lo, int hi)

private Object[]

Returns:

tmp, whether or not it grew
ensureCapacity
(int
the minimum required capacity of the tmp array
minCapacity
)

Ensures that the external array tmp has at least the specified number of elements, increasing its size if necessary.

private static int

Returns:

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. 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 should follow it.
gallopLeft
(Comparable<Object>
the key whose insertion point to search for
key
,
Object[]
the array in which to search
a
,
int
the index of the first element in the range
base
,
int
the length of the range; must be > 0
len
,
int
the index at which to begin the search, 0 <= hint < n. The closer hint is to the result, the faster this method will run.
hint
)

Locates the position at which to insert the specified key into the specified sorted range; if the range contains an element equal to key, returns the index of the leftmost equal element.

private static int

Returns:

the int k, 0 <= k <= n such that a[b + k - 1] <= key < a[b + k]
gallopRight
(Comparable<Object>
the key whose insertion point to search for
key
,
Object[]
the array in which to search
a
,
int
the index of the first element in the range
base
,
int
the length of the range; must be > 0
len
,
int
the index at which to begin the search, 0 <= hint < n. The closer hint is to the result, the faster this method will run.
hint
)

Like gallopLeft, except that if the range contains an element equal to key, gallopRight returns the index after the rightmost equal element.

private void
mergeAt(int
stack index of the first of the two runs to merge
i
)

Merges the two runs at stack indices i and i+1.

private void
mergeCollapse()

Examines the stack of runs waiting to be merged and merges adjacent runs until the stack invariants are reestablished: 1.

private void
mergeForceCollapse()

Merges all runs on the stack until only one remains.

private void
mergeHi(int
index of first element in first run to be merged
base1
,
int
length of first run to be merged (must be > 0)
len1
,
int
index of first element in second run to be merged (must be aBase + aLen)
base2
,
int
length of second run to be merged (must be > 0)
len2
)

Like mergeLo, except that this method should be called only if len1 >= len2; mergeLo should be called if len1 <= len2.

private void
mergeLo(int
index of first element in first run to be merged
base1
,
int
length of first run to be merged (must be > 0)
len1
,
int
index of first element in second run to be merged (must be aBase + aLen)
base2
,
int
length of second run to be merged (must be > 0)
len2
)

Merges two adjacent runs in place, in a stable fashion.

private static int

Returns:

the length of the minimum run to be merged
minRunLength
(int
the length of the array to be sorted
n
)

Returns the minimum acceptable run length for an array of the specified length.

private void
pushRun(int
index of the first element in the run
runBase
,
int
the number of elements in the run
runLen
)

Pushes the specified run onto the pending-run stack.

private static void
rangeCheck(int
the length of the array
arrayLen
,
int
the index of the first element of the range
fromIndex
,
int
the index after the last element of the range
toIndex
)

Checks that fromIndex and toIndex are in range, and throws an appropriate exception if they aren't.

private static void
reverseRange(Object[]
the array in which a range is to be reversed
a
,
int
the index of the first element in the range to be reversed
lo
,
int
the index after the last element in the range to be reversed
hi
)

Reverse the specified range of the specified array.

pack-priv static void
sort(Object[] a)

pack-priv static void
sort(Object[] a, int lo, int hi)

Inherited from java.lang.Object:
cloneequalsfinalizegetClasshashCodenotifynotifyAlltoStringwaitwaitwait

Field Detail

aback to summary
private Object[] a

The array being sorted.

DEBUGback to summary
private static final boolean DEBUG

Asserts have been placed in if-statements for performace. To enable them, set this field to true and enable them in VM with a command line flag. If you modify this class, please do test the asserts!

INITIAL_TMP_STORAGE_LENGTHback to summary
private static final int INITIAL_TMP_STORAGE_LENGTH

Maximum initial size of tmp array, which is used for merging. The array can grow to accommodate demand. Unlike Tim's original C version, we do not allocate this much storage when sorting smaller arrays. This change was required for performance.

MIN_GALLOPback to summary
private static final int MIN_GALLOP

When we get into galloping mode, we stay there until both runs win less often than MIN_GALLOP consecutive times.

MIN_MERGEback to summary
private static final int MIN_MERGE

This is the minimum sized sequence that will be merged. Shorter sequences will be lengthened by calling binarySort. If the entire 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 implementation, but 32 was empirically determined to work better in 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 minRunLength computation. If you decrease this constant, you must change the stackLen computation in the TimSort constructor, or you risk an ArrayOutOfBounds exception. See listsort.txt for a discussion of the minimum stack length required as a function of the length of the array being sorted and the minimum merge sequence length.

minGallopback to summary
private int minGallop

This controls when we get *into* galloping mode. It is reset to MIN_GALLOP before each sort. The mergeLo and mergeHi methods nudge it higher for random data, and lower for highly structured data.

runBaseback to summary
private final int[] runBase
runLenback to summary
private final int[] runLen
stackSizeback to summary
private int stackSize

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 true (so long as the indices are in bounds) that: runBase[i] + runLen[i] == runBase[i + 1] so we could cut the storage for this, but it's a minor amount, and keeping all the info explicit simplifies the code.

tmpback to summary
private Object[] tmp

Temp storage for merges.

tmpCountback to summary
private int tmpCount

Constructor Detail

ComparableTimSortback to summary
pack-priv ComparableTimSort()
ComparableTimSortback to summary
private ComparableTimSort(Object[] a)

Creates a TimSort instance to maintain the state of an ongoing sort.

Parameters
a:Object[]

the array to be sorted

Method Detail

binarySortback to summary
private static void binarySort(Object[] a, int lo, int hi, int start)

Sorts the specified portion of the specified array using a binary 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 movement (worst case). If the initial part of the specified range is already sorted, this method can take advantage of it: the method assumes that the elements from index lo, inclusive, to start, exclusive are already sorted.

Parameters
a:Object[]

the array in which a range is to be sorted

lo:int

the index of the first element in the range to be sorted

hi:int

the index after the last element in the range to be sorted

start:int

the index of the first element in the range that is not already known to be sorted (@code lo <= start <= hi}

Annotations
@SuppressWarnings:fallthrough
countRunAndMakeAscendingback to summary
private static int countRunAndMakeAscending(Object[] a, int lo, int hi)

Returns the length of the run beginning at the specified position in the specified array and reverses the run if it is descending (ensuring that the run will always be ascending when the method returns). A run is the longest ascending sequence with: a[lo] <= a[lo + 1] <= a[lo + 2] <= ... or the longest descending sequence with: a[lo] > a[lo + 1] > a[lo + 2] > ... For its intended use in a stable mergesort, the strictness of the definition of "descending" is needed so that the call can safely reverse a descending sequence without violating stability.

Parameters
a:Object[]

the array in which a run is to be counted and possibly reversed

lo:int

index of the first element in the run

hi:int

index after the last element that may be contained in the run. It is required that @code{lo < hi}.

Returns:int

the length of the run beginning at the specified position in the specified array

Annotations
@SuppressWarnings:unchecked
doSortback to summary
public void doSort(Object[] a, int lo, int hi)
ensureCapacityback to summary
private Object[] ensureCapacity(int minCapacity)

Ensures that the external array tmp has at least the specified number of elements, increasing its size if necessary. The size increases exponentially to ensure amortized linear time complexity.

Parameters
minCapacity:int

the minimum required capacity of the tmp array

Returns:Object[]

tmp, whether or not it grew

gallopLeftback to summary
private static int gallopLeft(Comparable<Object> key, Object[] a, int base, int len, int hint)

Locates the position at which to insert the specified key into the specified sorted range; if the range contains an element equal to key, returns the index of the leftmost equal element.

Parameters
key:Comparable<Object>

the key whose insertion point to search for

a:Object[]

the array in which to search

base:int

the index of the first element in the range

len:int

the length of the range; must be > 0

hint:int

the index at which to begin the search, 0 <= hint < n. The closer hint is to the result, the faster this method will run.

Returns:int

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. 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 should follow it.

gallopRightback to summary
private static int gallopRight(Comparable<Object> key, Object[] a, int base, int len, int hint)

Like gallopLeft, except that if the range contains an element equal to key, gallopRight returns the index after the rightmost equal element.

Parameters
key:Comparable<Object>

the key whose insertion point to search for

a:Object[]

the array in which to search

base:int

the index of the first element in the range

len:int

the length of the range; must be > 0

hint:int

the index at which to begin the search, 0 <= hint < n. The closer hint is to the result, the faster this method will run.

Returns:int

the int k, 0 <= k <= n such that a[b + k - 1] <= key < a[b + k]

mergeAtback to summary
private void mergeAt(int i)

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, i must be equal to stackSize-2 or stackSize-3.

Parameters
i:int

stack index of the first of the two runs to merge

Annotations
@SuppressWarnings:unchecked
mergeCollapseback to summary
private void mergeCollapse()

Examines the stack of runs waiting to be merged and merges adjacent runs until the stack invariants are reestablished: 1. runLen[n - 2] > runLen[n - 1] + runLen[n] 2. runLen[n - 1] > runLen[n] where n is the index of the last run in runLen. This method has been formally verified to be correct after checking the last 4 runs. Checking for 3 runs results in an exception for large arrays. (Source: http://envisage-project.eu/proving-android-java-and-python-sorting-algorithm-is-broken-and-how-to-fix-it/) 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 entry to the method.

mergeForceCollapseback to summary
private void mergeForceCollapse()

Merges all runs on the stack until only one remains. This method is called once, to complete the sort.

mergeHiback to summary
private void mergeHi(int base1, int len1, int base2, int len2)

Like mergeLo, except that this method should be called only if len1 >= len2; mergeLo should be called if len1 <= len2. (Either method may be called if len1 == len2.)

Parameters
base1:int

index of first element in first run to be merged

len1:int

length of first run to be merged (must be > 0)

base2:int

index of first element in second run to be merged (must be aBase + aLen)

len2:int

length of second run to be merged (must be > 0)

Annotations
@SuppressWarnings:unchecked
mergeLoback to summary
private void mergeLo(int base1, int len1, int base2, int len2)

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 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. For performance, this method should be called only when len1 <= len2; its twin, mergeHi should be called if len1 >= len2. (Either method may be called if len1 == len2.)

Parameters
base1:int

index of first element in first run to be merged

len1:int

length of first run to be merged (must be > 0)

base2:int

index of first element in second run to be merged (must be aBase + aLen)

len2:int

length of second run to be merged (must be > 0)

Annotations
@SuppressWarnings:unchecked
minRunLengthback to summary
private static int minRunLength(int n)

Returns the minimum acceptable run length for an array of the specified length. Natural runs shorter than this will be extended with binarySort. Roughly speaking, the computation is: 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 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. For the rationale, see listsort.txt.

Parameters
n:int

the length of the array to be sorted

Returns:int

the length of the minimum run to be merged

pushRunback to summary
private void pushRun(int runBase, int runLen)

Pushes the specified run onto the pending-run stack.

Parameters
runBase:int

index of the first element in the run

runLen:int

the number of elements in the run

rangeCheckback to summary
private static void rangeCheck(int arrayLen, int fromIndex, int toIndex)

Checks that fromIndex and toIndex are in range, and throws an appropriate exception if they aren't.

Parameters
arrayLen:int

the length of the array

fromIndex:int

the index of the first element of the range

toIndex:int

the index after the last element of the range

Exceptions
IllegalArgumentException:
if fromIndex > toIndex
ArrayIndexOutOfBoundsException:
if fromIndex < 0 or toIndex > arrayLen
reverseRangeback to summary
private static void reverseRange(Object[] a, int lo, int hi)

Reverse the specified range of the specified array.

Parameters
a:Object[]

the array in which a range is to be reversed

lo:int

the index of the first element in the range to be reversed

hi:int

the index after the last element in the range to be reversed

sortback to summary
pack-priv static void sort(Object[] a)
sortback to summary
pack-priv static void sort(Object[] a, int lo, int hi)