Post

Dark Sort in Java

Learn how Dark 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.

Dark Sort in Java

Introduction

Dark Sort is a non-comparison sort for non-negative integers, and in this implementation it is simply counting sort under another name. It counts how often each value occurs, in an array with one slot per value from 0 to the maximum, and then rewrites the input from those counts: every 0, then every 1, and so on.

Three ideas carry the whole algorithm:

  • One slot per value: the count array has a slot for every value from 0 to the largest value, so slot v counts how many times v occurs.
  • Counting instead of comparing: one pass over the input increments the slot of each value; no two values are ever compared with each other, apart from finding the maximum.
  • Rebuilding from the counts: walking the slots from 0 upwards and writing each value as many times as it was counted produces the sorted array.

The name doesn’t come from a well-known algorithm: Dark Sort appears in the TheAlgorithms/Java collection, where this implementation is the basic form of counting sort. The Counting Sort guide covers the full version, which shifts by the minimum and uses running totals so that it is stable. This simpler form is a good first look at sorting by counting, and a reminder that a new name doesn’t make a new algorithm.

This article uses basic counting sort on Integer arrays: count every value from 0 to the maximum, then overwrite the array in sorted order.

Performance Characteristics

Dark Sort never compares values, so its cost depends only on the number of values and on the largest value, not on their order.

Time Complexity

Time complexity describes how the number of steps an algorithm takes grows as the input gets larger.

In the table, $n$ is the number of values and $k$ is the largest value plus one, the number of count slots.

CaseTimeWhen it happens
Best$O(n + k)$Any input: the same three passes run every time
Average$O(n + k)$Any input
Worst$O(n + k)$Any input, but slow and memory-hungry when the largest value is huge

Why $n + k$? Finding the maximum and counting the values each walk the input once ($n$ work). Rebuilding walks all $k$ slots and writes each value once ($n + k$ work). When the values are small, the whole sort is linear.

Because the count array always starts at 0, a few large values make it huge, even when the values are close together: sorting {1_000_000, 1_000_001} creates a million slots. The Counting Sort version subtracts the minimum first, so it needs only max - min + 1 slots.

Space Complexity

Space complexity describes how much extra memory an algorithm needs, beyond the input itself, as the input gets larger.

PropertyValue
Space$O(k)$ for the count array
In placeThe output overwrites the input, but the values are rebuilt from counts, not moved
StableNot applicable: the values are rebuilt from counts, so there is no original order to keep

Algorithm (Pseudo Code)

Dark Sort starts by finding the largest value and creating a count array with one slot for every value from 0 up to it, all set to 0. Then it walks the input once and adds one to the slot of each value. After that pass, slot v says exactly how many times v occurs in the input.

To rebuild the array, it walks the slots from 0 upwards and writes each value into the input array as many times as its slot says, starting at index 0. Empty slots are skipped. Because the slots are visited in increasing order, the values are written in increasing order, and the array is sorted.

1
2
3
4
5
6
7
8
9
10
11
12
sort(unsorted):
    if unsorted has fewer than 2 values: return unsorted
    max = largest value
    temp = new int[max + 1]                   // one count per value 0 .. max
    for each value in unsorted:
        temp[value]++
    index = 0
    for i = 0 to max:
        while temp[i] > 0:
            unsorted[index++] = i
            temp[i]--
    return unsorted

After the counting pass, temp[v] holds the number of times v occurs, so writing every slot in order rebuilds the values in sorted order.

The array ends up sorted, but none of the original objects are moved: every slot writes the value i again, as a new Integer. For values above 127, those are different objects from the ones that went in, and anything attached to the original objects is lost. That’s why this form only works for plain numbers; counting sort with running totals moves the original items instead.

Visualization

The visualization below follows the Java code line by line, starting with ten values between 1 and 5.

Sorting by counting is about repeated values, so instead of the values 0 to 9, the visualization starts with [4, 2, 5, 4, 1, 3, 2, 4, 5, 2], the same values as the Counting Sort guide. Slot 0 stays empty, because Dark Sort always counts from 0.

Each step shows the array, the count array temp 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 new random values between 1 and 6.
  • Rows: the top row is the array being sorted, and the bottom row is temp, with the value each slot counts above it.
  • Pointer: I is index, the next position in the array to be written.
  • Colours: the value being counted, or the slot being emptied, is amber, the cells just written are salmon, and the part of the array that has been rewritten is green.
counted / slot being emptied written rewritten I = index

Java Code

The implementation is a DarkSort class with one public method, sort, for Integer arrays, and one private helper, findMax. It doesn’t implement the SortAlgorithm interface and doesn’t use the SortUtils helpers.

The complete code is in the algorithm-examples repository on GitHub: DarkSort.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
public Integer[] sort(Integer[] unsorted) {
    if (unsorted == null || unsorted.length <= 1) {
        return unsorted;
    }

    int max = findMax(unsorted);

    int[] temp = new int[max + 1];

    for (int value : unsorted) {
        temp[value]++;
    }

    int index = 0;
    for (int i = 0; i < temp.length; i++) {
        while (temp[i] > 0) {
            unsorted[index++] = i;
            temp[i]--;
        }
    }

    return unsorted;
}

sort returns null and arrays of zero or one value straight back. Otherwise it finds the largest value, creates temp with one slot per value from 0 to max, and counts: temp[value]++ for every value, which unboxes each Integer to an int. The second loop walks the slots in order, writes i into the array as many times as temp[i] says, and counts the slot down to 0. The array is overwritten in sorted order and returned.

The class Javadoc says it is for non-negative integers, but nothing checks that. A negative value makes temp[value] throw an ArrayIndexOutOfBoundsException, for example Index -1 out of bounds for length 4, a null element throws a NullPointerException when it is unboxed, Integer.MAX_VALUE overflows max + 1 and throws a NegativeArraySizeException, and a value around 500,000,000 runs out of memory with a 512 MB heap. A clear check up front, like the one in the repository’s PigeonholeSort and BeadSort, would give a better error, and subtracting the minimum, as in Counting Sort, would remove the negative and large-value problems.

findMax

1
2
3
4
5
6
7
8
9
private int findMax(Integer[] arr) {
    int max = arr[0];
    for (int value : arr) {
        if (value > max) {
            max = value;
        }
    }
    return max;
}

findMax walks the array once and keeps the largest value seen, which sets the size of the count array. It compares arr[0] with itself on the first iteration, which is harmless.

Running it

1
2
3
4
Integer[] numbers = {7, 2, 9, 4, 0, 8, 3, 6, 1, 5};
new DarkSort().sort(numbers);
System.out.println(Arrays.toString(numbers));
// [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]

Create a DarkSort, pass it an array, and the same array comes back sorted, overwritten with the counted values. The class is package-private, so the code must be in the com.javanibble.sort package.

Summary

  • Dark Sort is counting sort under another name: count how often each value occurs, then rewrite the array from the counts.
  • This implementation counts into a temp array with one slot for every value from 0 to the maximum and overwrites the input in sorted order.
  • After the counting pass, every slot holds the number of times its value occurs, so emptying the slots in order writes the values from smallest to largest.
  • It runs in $O(n + k)$ time with $O(k)$ extra space, where $k$ is the maximum plus one, and never compares two values apart from finding the maximum.
  • It only handles small, non-negative Integer values, without checking for them. The Counting Sort guide shows the full version, with a minimum shift and stable placement.
This post is licensed under CC BY 4.0 by the author.