man swift/sorting

How Swift sorts

lib / Swift 8 mindraft

checked against: Swift 6.4.2

What algorithm runs when you call sorted(by:) in Swift, and can you rely on equal elements keeping their order?

let ranked = scores.sorted { $0.points > $1.points }

Since Swift 5.0 the answer to the first question is a modified Timsort, and since Swift 5.8 the answer to the second is yes, in writing. This article reads stdlib/public/core/Sort.swift at the swift-6.4.2-RELEASE tag and checks it with small programs built with swiftc -O (Apple Swift 6.4.2) on an Apple M2 Pro. Every number below comes from that source, a Swift Evolution proposal, a commit message, or one of those programs.

The short version

sort(by:) sorts the array’s own storage in place. Arrays of up to 63 elements get a plain insertion sort. Longer ones are cut into runs. The algorithm finds stretches that are already ascending or strictly descending, reverses the descending ones, and extends any run shorter than a minimum length (32 to 64) with insertion sort. Runs go on a stack and are merged under Timsort’s size invariants, using a temporary buffer of half the array. The merge is a straight merge, without Timsort’s galloping mode. The result is stable, and the documentation has guaranteed that since Swift 5.8.

Entry points

sorted() calls sorted(by: <), and sorted(by:) copies the sequence into a ContiguousArray, sorts that in place and returns it as an Array (Sort.swift L46-L49, L130-L138). sort(by:) asks the collection for contiguous storage with withContiguousMutableStorageIfAvailable and runs _stableSortImpl on it. A collection without contiguous storage is sorted into a new array and copied back element by element (L245-L261). Every path ends in the same function, and all of them are @inlinable.

The driver

_stableSortImpl (L656-L712) is the whole algorithm in about 50 lines. Its doc comment says: “The adaptive algorithm used is Timsort, modified to perform a straight merge of the elements using a temporary buffer.”

minrun = _minimumMergeRunLength(count)
if count <= minrun: insertion sort everything, done
buffer = uninitialized space for count / 2 elements
runs = []
start = 0
while start < count:
    (end, descending) = _findNextRun(from: start)
    if descending: reverse start..<end
    if end - start < minrun and end < count:
        extend the run to minrun elements with insertion sort
    push start..<end on runs
    _mergeTopRuns(runs)       merge until the invariants hold
    start = end
_finalizeRuns(runs)           merge what is left, last two first

The buffer comes from Array(unsafeUninitializedCapacity: count / 2), so a sort of a million elements allocates space for 500,000 more.

Minimum run length

_minimumMergeRunLength (L451-L474) quotes Tim Peters’ listsort.txt. It takes the top six bits of the count and adds one if any lower bit is set. I copied the function into a program and printed it for a few sizes:

$ swiftc -O minrun.swift -o minrun && ./minrun
63 63
64 32
65 33
100 50
1000 63
50000 49
1000000 62

The doc comment above the function says it returns c when c <= 64. The code checks c < 1 << 6, so at exactly 64 it returns 32. The driver’s count <= minimumRunLength test therefore sends 63 elements to insertion sort and 64 to the run-finding path. Counting comparisons shows the switch:

func comparisons(_ a: [Int]) -> Int {
    var a = a
    var calls = 0
    a.sort { calls += 1; return $0 < $1 }
    return calls
}
for n in [63, 64] {
    let up = Array(0..<n)
    print("n=\(n): ascending \(comparisons(up)), descending \(comparisons(up.reversed()))")
}
$ swiftc -O comparisons.swift -o comparisons && ./comparisons
n=63: ascending 62, descending 1953
n=64: ascending 63, descending 63

Reversed input of 63 elements costs 63 × 62 / 2 = 1,953 comparisons, the insertion sort’s worst case. One element more, and the run finder sees one descending run of 64, reverses it, and is done after 63 comparisons.

Insertion sort

_insertionSort (L264-L297) takes each new element and swaps it backwards with swapAt while it compares less than its left neighbour. It stops at the first neighbour that isn’t greater, so an element never passes an equal one. That keeps it stable, and an already sorted range costs one comparison per element.

Finding runs

_findNextRun (L476-L511) compares the first two elements to decide the direction, then walks while the direction holds. Its comment gives the rule. “An ascending run can include consecutive equal elements, but because a descending run will be reversed, it must be strictly descending.” Reversing a run with equal elements in it would swap their order and break stability.

That rule has a cost I didn’t expect. In a descending array with repeated values, a descending run ends at the first pair of equal neighbours. The driver pads that short run to the minimum length with insertion sort over descending data, its worst case, and the next search starts after the padding, where the same thing can happen again. Timing four kinds of input:

let random = (0..<1_000_000).map { _ in Int.random(in: 0..<1_000_000, using: &rng) }
let ascending = random.sorted()          // has repeated values
let descending = Array(ascending.reversed())
let distinctDescending = Array((0..<1_000_000).reversed())
// each sorted 5 times, counting comparisons, best time kept
$ swiftc -O sorttime.swift -o sorttime && ./sorttime
random: 30148897 comparisons, best of 5 0.102289916 seconds
ascending: 999999 comparisons, best of 5 0.002036583 seconds
descending: 37411933 comparisons, best of 5 0.074772041 seconds
descending, distinct: 999999 comparisons, best of 5 0.002250084 seconds

Sorted input in either direction costs n − 1 comparisons and about 2 ms, when the descending values are distinct. The same million values in descending order, with duplicates, took 37.4 million comparisons, more than the 30.1 million for random order. It was still faster than random input, 75 ms against 102 ms.

Merging

_merge (L332-L449) merges two adjacent sorted ranges. It moves the shorter of the two into the buffer, which is why the buffer only needs half the array. If the lower half is shorter it merges from the front, otherwise from the back. On a tie it takes the element from the lower range: from the front, it moves the right element only when areInIncreasingOrder(right, left) is true, and from the back it does the mirror image. The comments in both loops say “preferring the buffer when equal to maintain stability”. There is no galloping: each step makes one comparison and moves one element.

_mergeTopRuns (L551-L629) keeps Timsort’s invariants on the run stack: for the top runs W, X, Y and Z, W > X + Y, X > Y + Z and Y > Z. When one of the first two fails it merges Y with the smaller of X and Z; when only Y > Z fails it merges Y and Z. It repeats until all three hold, and since it runs after every new run, the whole stack keeps the invariants. Finally _finalizeRuns (L631-L654) merges whatever is left, from the top of the stack down.

For a shuffled array of 50,000 integers, where the minimum run length is 49, three runs gave between 1,141,301 and 1,144,637 comparisons, about 1.46 times n log₂ n:

print((0..<50_000).shuffled().count, comparisons((0..<50_000).shuffled()))
$ swiftc -O shuffled.swift -o shuffled && ./shuffled && ./shuffled && ./shuffled
50000 1141842
50000 1141301
50000 1144637

Stable, and since when

At 6.4.2 every sort entry point says “The sorting algorithm is guaranteed to be stable” (L40, L120, L165, L234). The swift-5.7-RELEASE source says “is not guaranteed to be stable” at the same lines, as do the 5.0, 5.5 and 5.6 tags I checked, although the code was already the stable merge sort. SE-0372 changed only the documentation; its text says “Swift’s sorting algorithm was changed to be stable before Swift 5, but we’ve never updated the documentation to provide that guarantee.”

Stability decides how ties come out, so the direction of the comparison matters:

let words = ["pear", "fig", "plum", "kiwi", "apple", "lime"]
print(words.sorted { $0.count < $1.count })
print(words.sorted { $0.count > $1.count })
print(words.sorted { $0.count < $1.count }.reversed() as [String])
$ swiftc -O stable.swift -o stable && ./stable
["fig", "pear", "plum", "kiwi", "lime", "apple"]
["apple", "pear", "plum", "kiwi", "lime", "fig"]
["apple", "lime", "kiwi", "plum", "pear", "fig"]

Sorting longest first with > keeps the four-letter words in their original order. Sorting shortest first and reversing puts them backwards.

Curious facts

  • An array of 63 elements in reverse order costs 1,953 comparisons; one of 64 costs 63.
  • The doc comment of _minimumMergeRunLength says it returns c for c <= 64; the code returns 32 for 64.
  • A descending array with duplicate values took more comparisons (37.4 million) than the same values shuffled (30.1 million).
  • _merge and _mergeRuns return a Bool that nothing uses. The comment calls it legacy ABI, added as a workaround for a compiler bug that has since been fixed (L332-L338).
  • If the comparison closure throws partway through, the documentation of sort(by:) promises that “the elements may be in a different order, but none will be lost” (L238-L242). The merge’s defer block moves any elements still in the buffer back into the array.

History

  • Swift 4.2 and earlier: an introsort, with _introSort, _insertionSort and _heapSort generated from Sort.swift.gyb.
  • November 2018: commit e5c1567957 (PR #19717) “switches the standard library’s sort algorithm from an in-place introsort to use a modified timsort”, noting that it “performs straight merges instead of adopting timsort’s galloping strategy”. The swift-5.0-RELEASE tag has _stableSortImpl.
  • Swift 5.0 to 5.7: stable in practice, documented as “not guaranteed to be stable”.
  • Swift 5.8: SE-0372, “Document Sorting as Stable”, implemented by commit 7ce1f3e722 (August 2022), which changed the documentation and nothing else.

Sources

ls swift/