Library Sort in Java
Learn how Library Sort works: its time and space complexity, the algorithm in pseudo code, and a step-by-step visualisation that follows the Java code line by line.
Introduction
Library Sort, also called gapped insertion sort, is a comparison sort that fixes insertion sort’s biggest cost. Insertion sort spends most of its time shifting values to make room. Library Sort leaves gaps between the values, like a librarian who keeps some empty space on every shelf, so that most new values can be put straight into a gap.
Three ideas carry the whole algorithm:
- A shelf with gaps: the values are kept in sorted order in an array twice as large as needed; the empty slots are gaps.
- Binary search, then a short shift: a new value’s place is found with a binary search, and when that slot is taken, only the values up to the nearest gap move one position.
- Rebalancing in rounds: values are inserted in rounds of 1, 2, 4, 8, … values; after each round, all values are spread out evenly again, so every part of the shelf has gaps for the next round.
Michael Bender, Martín Farach-Colton and Miguel Mosteiro analysed Library Sort in 2004 and showed that, when the values arrive in random order, it runs in $O(n \log n)$ time with high probability, instead of insertion sort’s $O(n^2)$. It shows how a little extra space can turn a quadratic algorithm into a fast one, an idea also used in data structures such as packed-memory arrays.
This article uses Library Sort on int arrays with a gap factor of 2: the shelf has twice as many slots as there are values, and rounds of doubling size are followed by an even redistribution.
Performance Characteristics
Library Sort’s speed depends on whether new values spread out over the shelf: then they find gaps nearby, but if they all land in the same place, the gaps there run out.
Time Complexity
Time complexity describes how the number of steps an algorithm takes grows as the input gets larger.
| Case | Time | When it happens |
|---|---|---|
| Best | $O(n \log n)$ | Values arriving in random order: almost every insertion finds a gap close by |
| Average | $O(n \log n)$ | Random order, with high probability |
| Worst | $O(n^2)$ | Sorted or reverse-sorted input: every new value lands at the same end of the shelf |
Why $n \log n$? Each insertion makes a binary search, $O(\log n)$ probes, and with random input the nearest gap is a constant distance away on average, so the shift is short. The rebalancing after each round touches every slot once, and since the rounds double in size, there are only $O(\log n)$ of them, costing $O(n \log n)$ in total. When every new value goes to the same end, though, the gaps there fill up within a round, and each further value shifts a longer and longer run of values. With the repository code, a million random values take about 0.2 seconds, but a million already sorted values take about 48 seconds.
The $O(n \log n)$ guarantee assumes the values are inserted in random order. Shuffling the input first, in $O(n)$, makes sorted and reverse-sorted input as fast as random input.
Space Complexity
Space complexity describes how much extra memory an algorithm needs, beyond the input itself, as the input gets larger.
| Property | Value |
|---|---|
| Space | $O(n)$: a shelf of $2n$ slots, a matching array of occupied flags, and a buffer for rebalancing |
| In place | No (the values are built up on a separate, larger shelf) |
| Stable | Not applicable here: the code sorts plain int values, where equal values can’t be told apart |
Algorithm (Pseudo Code)
Library Sort starts with an empty shelf twice the size of the input and puts the first value in the middle. Then it inserts the remaining values in rounds: one value, then two, then four, and so on. For each value, a binary search over the shelf finds the position just after all the values that are smaller or equal. If that slot is a gap, the value goes straight in. If not, the values between that slot and the nearest gap, to the left or the right, whichever is closer, move one slot towards the gap, and the value goes into the freed slot.
After each round, the shelf is rebalanced: all values are taken off and put back with equal spacing, so that gaps are spread evenly again before the next, larger round. When every value has been inserted, the occupied slots, read from left to right, are the sorted array.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
sort(array):
data = new int[2n], occupied = new boolean[2n]
data[n] = array[0]
round = 0, next = 1
while next < n:
for each of the next min(2^round, n - next) values v:
insert(data, occupied, v)
round++
if values remain: rebalance(data, occupied, filled)
copy the occupied slots of data back into array, in order
insert(v):
pos = first slot whose value (or next value to the right) is greater than v
if slot pos is empty: put v there
else: shift the run up to the nearest gap one slot towards it, put v in the freed slot
rebalance(filled):
collect the values in order, then place value k at slot k * capacity / filled
The occupied slots of the shelf are always in sorted order, so reading them from left to right at the end gives the sorted array.
The binary search has to look at gaps, too. The code treats an empty slot as if it held the next value to its right, which keeps the probe values in increasing order from left to right, so the search still works on a shelf full of holes.
Visualization
The visualization below follows the Java code step by step, starting with the values 0 to 9 in shuffled order.
Each step shows the input, the shelf of 20 slots and the line of code that is running, with a short explanation of what just happened:
- Step through: use the arrows to move one step forward or back, or drag the slider to jump to any step.
- Play: press Play to run the steps automatically, and press it again to pause.
- Shuffle: press the shuffle button to start again with a new random order.
- Input: the top row is the input. The value being inserted is amber; values already on the shelf fade out.
- Shelf: the bottom row is the shelf. Dashed slots are gaps. The value just inserted is salmon, values that had to shift are amber, and after a rebalance the evenly spread values are green.
- Rounds: the footer shows the round and how many slots have been shifted in total; with gaps everywhere, that number stays small.
Java Code
The implementation is a LibrarySort utility class: it is final, has a private constructor, and offers one public static method, sort, for int arrays. The constant GAP_FACTOR = 2 sets the shelf to twice the input size. The private methods split up the work: insert places one value, insertAtEnd handles a new largest value, findInsertionIndex and nearestOccupiedValueAtOrAfter do the binary search over a shelf with gaps, and rebalance spreads the values out again. The class doesn’t use the SortUtils helpers.
The complete code is in the algorithm-examples repository on GitHub:
LibrarySort.java.
sort
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
public static int[] sort(final int[] array) {
if (array == null) {
throw new IllegalArgumentException("Input array must not be null.");
}
if (array.length <= 1) {
return array;
}
final int n = array.length;
final int capacity = GAP_FACTOR * n;
final int[] data = new int[capacity];
final boolean[] occupied = new boolean[capacity];
final int mid = capacity / 2;
data[mid] = array[0];
occupied[mid] = true;
int filled = 1;
int nextToInsert = 1;
int round = 0;
while (nextToInsert < n) {
final int roundSize = Math.min(1 << round, n - nextToInsert);
for (int i = 0; i < roundSize; i++) {
insert(data, occupied, array[nextToInsert + i]);
filled++;
}
nextToInsert += roundSize;
round++;
if (nextToInsert < n) {
rebalance(data, occupied, filled);
}
}
int idx = 0;
for (int i = 0; i < capacity; i++) {
if (occupied[i]) {
array[idx++] = data[i];
}
}
return array;
}
sort rejects null with an IllegalArgumentException, returns arrays of zero or one value straight back, and creates the shelf: data for the values and occupied to tell values from gaps, since every int is a valid value. The first value goes in the middle. The main loop inserts the values in rounds of 1 << round values, 1, 2, 4, 8, …, and rebalances between rounds, but not after the last one. Finally the occupied slots are copied back into array in order.
The values are inserted in the order they come. Library Sort’s $O(n \log n)$ bound assumes random order, and this code doesn’t shuffle, so sorted and reverse-sorted input are quadratic: with the repository code, 100,000 sorted values take about 0.4 seconds and 1,000,000 take about 48 seconds, while 1,000,000 random values take about 0.2 seconds. Shuffling
arraybefore the main loop, and sorting the shuffled copy, fixes the bad cases.
findInsertionIndex and nearestOccupiedValueAtOrAfter
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
private static int findInsertionIndex(final int[] data, final boolean[] occupied, final int value) {
int lo = 0;
int hi = data.length;
while (lo < hi) {
final int mid = lo + (hi - lo) / 2;
final int probe = nearestOccupiedValueAtOrAfter(data, occupied, mid);
if (probe != Integer.MAX_VALUE && probe <= value) {
lo = mid + 1;
} else {
hi = mid;
}
}
return lo;
}
private static int nearestOccupiedValueAtOrAfter(final int[] data, final boolean[] occupied, final int index) {
for (int i = index; i < data.length; i++) {
if (occupied[i]) {
return data[i];
}
}
return Integer.MAX_VALUE;
}
findInsertionIndex is a binary search for the first slot whose value is greater than value. An empty slot is given the value of the nearest occupied slot to its right, and slots after the last value count as infinitely large, using Integer.MAX_VALUE as a marker. That keeps the probes in increasing order, which is all a binary search needs.
Two details are worth noticing:
nearestOccupiedValueAtOrAfterwalks right until it finds a value. After a rebalance the gaps are single slots, so the walk is short, but early in a round, or on a stretch of shelf with no values, one probe can scan many slots.- Because
Integer.MAX_VALUEdoubles as the “no value” marker, a realInteger.MAX_VALUEon the shelf is treated as larger than everything. NewInteger.MAX_VALUEvalues are then inserted before it rather than after, which still leaves the shelf sorted, since equalintvalues are interchangeable.
insert
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
private static void insert(final int[] data, final boolean[] occupied, final int value) {
final int pos = findInsertionIndex(data, occupied, value);
if (pos >= data.length) {
insertAtEnd(data, occupied, value);
return;
}
if (!occupied[pos]) {
data[pos] = value;
occupied[pos] = true;
return;
}
int right = pos;
while (right < data.length && occupied[right]) {
right++;
}
int left = pos - 1;
while (left >= 0 && occupied[left]) {
left--;
}
final boolean canGoRight = right < data.length;
final boolean canGoLeft = left >= 0;
if (canGoRight && (!canGoLeft || (right - pos) <= (pos - left))) {
System.arraycopy(data, pos, data, pos + 1, right - pos);
occupied[right] = true;
data[pos] = value;
} else if (canGoLeft) {
System.arraycopy(data, left + 1, data, left, pos - 1 - left);
occupied[left] = true;
data[pos - 1] = value;
} else {
throw new IllegalStateException("No gap available for insertion; rebalance too infrequent.");
}
}
insert puts one value on the shelf. If the found slot is a gap, the value simply goes in. Otherwise it looks for the nearest gap on both sides and shifts the shorter run: to the right, the values from pos up to the gap move one slot right and the value takes pos; to the left, the values between the gap and pos move one slot left and the value takes pos - 1. Either way, the shelf stays sorted. The final IllegalStateException is a guard that can’t trigger, since the shelf is never more than half full.
insertAtEnd
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
private static void insertAtEnd(final int[] data, final boolean[] occupied, final int value) {
final int last = data.length - 1;
if (!occupied[last]) {
data[last] = value;
occupied[last] = true;
return;
}
int left = last - 1;
while (left >= 0 && occupied[left]) {
left--;
}
if (left < 0) {
throw new IllegalStateException("No gap available for insertion; rebalance too infrequent.");
}
System.arraycopy(data, left + 1, data, left, last - left);
occupied[left] = true;
data[last] = value;
}
insertAtEnd handles a value larger than everything on the shelf when the last slot is already taken: there is no room to its right, so the run of values ending at the last slot shifts one slot left into the nearest gap, and the new value takes the last slot. On sorted input, every value takes this path, and the run at the end grows with every insertion in a round, which is where the quadratic time comes from.
rebalance
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
private static void rebalance(final int[] data, final boolean[] occupied, final int filled) {
final int capacity = data.length;
final int[] temp = new int[filled];
int idx = 0;
for (int i = 0; i < capacity; i++) {
if (occupied[i]) {
temp[idx++] = data[i];
}
}
Arrays.fill(occupied, false);
for (int k = 0; k < filled; k++) {
final int pos = (int) ((long) k * capacity / filled);
data[pos] = temp[k];
occupied[pos] = true;
}
}
rebalance collects the values in order and puts value k back at slot k * capacity / filled, so they are spread evenly with gaps between them. The multiplication is done in long to avoid overflow on large arrays. Since the rounds double in size, the shelf is rebalanced only $O(\log n)$ times.
Running it
1
2
3
4
int[] numbers = {7, 2, 9, 4, 0, 8, 3, 6, 1, 5};
LibrarySort.sort(numbers);
System.out.println(Arrays.toString(numbers));
// [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
Call the static sort method; numbers itself is sorted, and the same array is also returned. The method takes a plain int[].
Summary
- Library Sort is a gapped insertion sort: it keeps the values sorted on a shelf with gaps, so most new values can be put in without shifting the others.
- This implementation uses a shelf twice the input size, inserts values in rounds of doubling size with a binary search, and rebalances the shelf between rounds.
- The occupied slots are always in sorted order, so reading them from left to right at the end gives the sorted array.
- It runs in $O(n \log n)$ on randomly ordered input but $O(n^2)$ on sorted or reverse-sorted input in this code, and needs $O(n)$ extra space.
- Shuffle the input first to get the expected $O(n \log n)$. For everyday sorting,
Arrays.sort()is faster; Library Sort is mainly a lesson in how spare space can save work, as in Insertion Sort taken a step further.
