ブリットソートを使用する

ブリットソート (blitsort) は、固定長の小さなスワップ領域と配列回転を使い、安定かつほぼインプレースに整列するハイブリッド比較ソートである。

整列度が低い区間では回転クイックソート、整列度が高い区間では回転マージソートを使い分ける。

回転クイックではピボットで安定分割して再帰する。区間がスワップ以下なら二重書き込みで分け、それより長い区間は半分に再帰したあと中央帯を回転でつなぐ。回転マージでは、隣接する整列済みランの左中央を取り、右ランでそれ未満の個数を二分探索してから回転し、スワップに収まるまで小さくして安定マージする。

本記事では高速な三区間回転や単境界の二分探索、分岐の少ない分割の代わりに、分かりやすい回転・通常の二分探索・二重書き込み分割を用いて簡略化している。小区間の仕上げは挿入ソート、回転マージを打ち切ったあとは通常の安定マージで代用する。

  1. アナライザ: 全体が昇順なら何もしない。降順(同値を含む非増加)なら反転して終了する。配列を 4 分割し、各区間の隣接昇順ペアが半数超ならその区間を回転マージソートで仕上げる。
  2. 回転クイックソート: 9 点の準中央値をピボットにし、スワップ長以下なら安定な二重書き込み分割、それより長い区間は半分ずつ分割してから中央帯を回転して <= ピボット を前方へ集める。
  3. 等値の第二走査: 右側が空(すべて <= ピボット)なら、< ピボット だけを前方へ寄せて等値帯を再帰から外す。
  4. 不均衡フォールバック: 左右の長さ比が 1:16 を超えて偏ったら、両側を回転マージソートする。最悪計算量を \(O(n \log n)\) に抑えるためのガードである。
  5. 回転マージ: 左ランの中央要素を取り、右ランでそれ未満の個数を二分探索し、中央ブロックを回転してから左右を再帰する。どちらかがスワップに収まったら通常の安定マージで打ち切る。
  6. 小区間: 要素数が閾値未満なら挿入ソートで仕上げる。スワップは既定で 512 要素(配列がそれより短ければ配列長)に固定する。
procedure blit_rotate(A, left, swap)
  // 先頭 left 個を末尾へ移す。短い側が swap に収まるなら block move、
  // そうでなければ 3 回の reverse(三区間回転の説明用代用)

procedure blit_stable_partition(A, swap, pivot)
  if length(A) > length(swap) then
    h := length(A) / 2
    l := blit_stable_partition(A[0 .. h), swap, pivot)
    r := blit_stable_partition(A[h .. end), swap, pivot)
    blit_rotate(A[l .. h+r), h - l, swap)
    return l + r
  // さもなくば swap へ退避して <= pivot を前方へ安定に書き戻す

procedure blit_rotate_merge_block(A, left_len, right_len, swap)
  if A[left_len-1] <= A[left_len] then return
  if left_len <= length(swap) or right_len <= length(swap) then
    stable_merge via swap; return
  rblock := left_len / 2; lblock := left_len - rblock
  left := lower_bound(A[left_len ..), A[lblock])
  blit_rotate(A[lblock .. lblock+rblock+left), rblock, swap)
  blit_rotate_merge_block(A[0 .. lblock+left), lblock, left, swap)
  blit_rotate_merge_block(A[lblock+left ..), rblock, right_len-left, swap)

procedure blitsort(A)
  if A is sorted then return
  if A is reverse-sorted then reverse(A); return
  swap := buffer of min(512, length(A))
  for each quarter Q of A
    if ordered_pairs(Q) > half then blit_rotate_mergesort(Q, swap)
  if A is sorted then return
  blit_partition_sort(A, swap)

最良は整列済み検出により \(O(n)\)、平均・最悪は \(O(n \log n)\) である。補助メモリは固定長スワップ(既定 512 要素)に加え、再帰の深さ分の \(O(\log n)\) のスタックを使う。

以下のデモでは視認性のため挿入閾値を 4、スワップを 4、不均衡判定を 1/4 に緩めている。

類似アルゴリズムとの相違点

フラックスソートは安定な二重書き込み分割と最大 \(O(n)\) の補助配列を使う。ブリットソートは同じ安定分割の発想を、固定スワップ+回転の組立に落とし込み、補助メモリを定数寄りに抑える。

クラムソートはフルクラム分割で不安定・インプレース寄りにする。ブリットソートは安定性を保ったまま回転で区間を寄せる点が対照的である。

クワッドソートはボトムアップのクワッドマージが本体である。ブリットソートは整列度が高いときだけ回転マージへ寄せ、ランダム寄りでは回転クイックを主とする。

ウィキソートやグレイルソートも小さなバッファで安定なインプレース寄りマージを目指すが、ブロックマージと内部バッファの設計が中心である。ブリットソートはクイック型の分割と回転マージのハイブリッドである。

時間計算量および空間計算量を計測する

Size Average time (s) Maximum time (s) Average memory (KiB) Maximum memory (KiB)
256 0.000007 0.000046 2 2
512 0.000015 0.000084 4 4
1024 0.000032 0.000094 4 4
2048 0.000066 0.000399 4 4
4096 0.000140 0.000226 4 4
8192 0.000304 0.000481 4 4
16384 0.000669 0.001586 4 4
32768 0.001434 0.002856 4 4
65536 0.003136 0.004310 4 4
131072 0.006816 0.009194 4 4
262144 0.014779 0.022818 4 4
計測に使用したコードを表示する

#!/usr/bin/env swift
import Foundation

// This standalone Swift driver creates the same temporary Docker build
// context as the former shell wrapper.  The benchmark program itself remains
// embedded below so readers can copy one complete, reproducible file.
struct BenchmarkError: Error, CustomStringConvertible {
    let message: String

    var description: String { message }

    init(_ message: String) {
        self.message = message
    }
}

func runCommand(_ executable: String, _ arguments: [String]) throws {
    let process = Process()
    process.executableURL = URL(fileURLWithPath: "/usr/bin/env")
    process.arguments = [executable] + arguments
    process.standardInput = FileHandle.standardInput
    process.standardOutput = FileHandle.standardOutput
    process.standardError = FileHandle.standardError

    do {
        try process.run()
    } catch {
        throw BenchmarkError("Could not start \(executable): \(error)")
    }
    process.waitUntilExit()
    guard process.terminationStatus == 0 else {
        throw BenchmarkError(
            "Command failed (\(process.terminationStatus)): " +
            "\(executable) \(arguments.joined(separator: " "))"
        )
    }
}

do {
    // The UUID avoids collisions when two benchmark copies are run at once.
    let workdir = FileManager.default.temporaryDirectory
        .appendingPathComponent("swift-sort-benchmark-\(UUID().uuidString)")
    try FileManager.default.createDirectory(at: workdir, withIntermediateDirectories: true)
    defer { try? FileManager.default.removeItem(at: workdir) }

    // A raw Swift string is used so the nested main.swift keeps its own
    // interpolation expressions such as \(seed) until Docker compiles it.
    let dockerfile = #"""
FROM swift:6.0

WORKDIR /app

RUN cat > alloc_track.c <<'ALLOC'
#define _GNU_SOURCE
#include <dlfcn.h>
#include <malloc.h>
#include <stdatomic.h>
#include <stddef.h>
#include <stdint.h>
#include <stdlib.h>
#include <string.h>

static atomic_size_t live_bytes = 0;
static atomic_size_t peak_bytes = 0;

static void *(*real_malloc)(size_t) = NULL;
static void *(*real_calloc)(size_t, size_t) = NULL;
static void *(*real_realloc)(void *, size_t) = NULL;
static void (*real_free)(void *) = NULL;

static void init_reals(void) {
    if (real_malloc) {
        return;
    }
    real_malloc = (void *(*)(size_t))dlsym(RTLD_NEXT, "malloc");
    real_calloc = (void *(*)(size_t, size_t))dlsym(RTLD_NEXT, "calloc");
    real_realloc = (void *(*)(void *, size_t))dlsym(RTLD_NEXT, "realloc");
    real_free = (void (*)(void *))dlsym(RTLD_NEXT, "free");
}

static void record_alloc(size_t size) {
    size_t live = atomic_fetch_add(&live_bytes, size) + size;
    size_t peak = atomic_load(&peak_bytes);
    while (live > peak) {
        if (atomic_compare_exchange_weak(&peak_bytes, &peak, live)) {
            break;
        }
    }
}

void alloc_track_reset_peak(void) {
    atomic_store(&peak_bytes, atomic_load(&live_bytes));
}

size_t alloc_track_live(void) { return atomic_load(&live_bytes); }
size_t alloc_track_peak(void) { return atomic_load(&peak_bytes); }

void *malloc(size_t size) {
    init_reals();
    void *p = real_malloc(size);
    if (p) {
        record_alloc(malloc_usable_size(p));
    }
    return p;
}

void *calloc(size_t nmemb, size_t size) {
    init_reals();
    void *p = real_calloc(nmemb, size);
    if (p) {
        record_alloc(malloc_usable_size(p));
    }
    return p;
}

void *realloc(void *ptr, size_t size) {
    init_reals();
    size_t old_size = 0;
    if (ptr) {
        old_size = malloc_usable_size(ptr);
    }
    void *p = real_realloc(ptr, size);
    if (p) {
        atomic_fetch_sub(&live_bytes, old_size);
        record_alloc(malloc_usable_size(p));
    } else if (size == 0) {
        atomic_fetch_sub(&live_bytes, old_size);
    }
    return p;
}

void free(void *ptr) {
    init_reals();
    if (ptr) {
        atomic_fetch_sub(&live_bytes, malloc_usable_size(ptr));
        real_free(ptr);
    }
}

ALLOC

RUN cat > main.swift <<'SWIFT'
import Foundation
#if canImport(Glibc)
import Glibc
#elseif canImport(Darwin)
import Darwin
#endif

@_silgen_name("alloc_track_live") func alloc_track_live() -> Int
@_silgen_name("alloc_track_peak") func alloc_track_peak() -> Int
@_silgen_name("alloc_track_reset_peak") func alloc_track_reset_peak()

extension UnsafeMutableBufferPointer where Element == Int {
    func swapAt(_ i: Int, _ j: Int) {
        let t = self[i]; self[i] = self[j]; self[j] = t
    }
}

let MIN_POWER: Int = 8
let MAX_POWER: Int = 18
let RUNS: Int = 8192
func insertion_sort(_ a: inout [Int]) {
    a.withUnsafeMutableBufferPointer { insertion_sort($0) }
}

func insertion_sort(_ a: UnsafeMutableBufferPointer<Int>) {
    if a.count < 2 {
        return
    }
    for i in 1..<a.count {
        var j = i
        while j > 0 && a[j - 1] > a[j] {
            a.swapAt(j - 1, j)
            j -= 1
        }
    }
}



/// Educational stand-in for scandum's blitsort (rotate merge / rotate quick).
/// Production uses trinity rotations, monobound binary search, quadsort blocks,
/// and branchless partitioning; here those are replaced with clearer routines
/// and a fixed swap of `BLIT_SWAP` elements (default 512, as in the reference).

let BLIT_SWAP = 512
let BLIT_OUT = 24

func blit_reverse_range(_ a: UnsafeMutableBufferPointer<Int>) {
    var lo = 0
    var hi = a.count
    while lo + 1 < hi {
        hi -= 1
        a.swapAt(lo, hi)
        lo += 1
    }
}

func blit_is_sorted(_ a: UnsafeMutableBufferPointer<Int>) -> Bool {
    if a.count < 2 {
        return true
    }
    for i in 1..<a.count {
        if a[i - 1] > a[i] {
            return false
        }
    }
    return true
}

func blit_is_reverse_sorted(_ a: UnsafeMutableBufferPointer<Int>) -> Bool {
    if a.count < 2 {
        return true
    }
    for i in 1..<a.count {
        if a[i - 1] < a[i] {
            return false
        }
    }
    return true
}

func blit_reverse(_ a: UnsafeMutableBufferPointer<Int>) {
    blit_reverse_range(a)
}

func blit_ordered_pairs(_ a: UnsafeMutableBufferPointer<Int>) -> Int {
    if a.count < 2 {
        return 0
    }
    var count = 0
    for i in 1..<a.count {
        if a[i - 1] <= a[i] {
            count += 1
        }
    }
    return count
}

func blit_median3_idx(_ a: UnsafeMutableBufferPointer<Int>, _ i: Int, _ j: Int, _ k: Int) -> Int {
    let x = a[i]
    let y = a[j]
    let z = a[k]
    if x < y {
        if y < z {
            return j
        } else if x < z {
            return k
        } else {
            return i
        }
    } else if x < z {
        return i
    } else if y < z {
        return k
    } else {
        return j
    }
}

func blit_quasimedian9(_ a: UnsafeMutableBufferPointer<Int>) -> Int {
    let n = a.count
    if n < 9 {
        return a[n / 2]
    }
    let step = n / 8
    let i0 = 0
    let i1 = step
    let i2 = step * 2
    let i3 = step * 3
    let i4 = step * 4
    let i5 = step * 5
    let i6 = step * 6
    let i7 = step * 7
    let i8 = n - 1
    let m0 = blit_median3_idx(a, i0, i1, i2)
    let m1 = blit_median3_idx(a, i3, i4, i5)
    let m2 = blit_median3_idx(a, i6, i7, i8)
    return a[blit_median3_idx(a, m0, m1, m2)]
}

/// Rotate `a` so the prefix of length `left` moves after the suffix.
/// Prefer a swap-assisted block move; otherwise fall back to three reverses
/// (educational stand-in for trinity / bridge rotations).
func blit_rotate(_ a: UnsafeMutableBufferPointer<Int>, _ left: Int, _ swap: UnsafeMutableBufferPointer<Int>) {
    let n = a.count
    if left == 0 || left == n {
        return
    }
    let right = n - left
    let swap_cap = swap.count

    if left <= right {
        if left <= swap_cap {
            for i in 0..<left {
                swap[i] = a[i]
            }
            let moved = Array(a[left..<n])
            for i in 0..<moved.count {
                a[i] = moved[i]
            }
            for i in 0..<left {
                a[right + i] = swap[i]
            }
            return
        }
    } else if right <= swap_cap {
        for i in 0..<right {
            swap[i] = a[left + i]
        }
        let moved = Array(a[0..<left])
        for i in 0..<moved.count {
            a[right + i] = moved[i]
        }
        for i in 0..<right {
            a[i] = swap[i]
        }
        return
    }

    blit_reverse_range(UnsafeMutableBufferPointer(rebasing: a[0..<left]))
    blit_reverse_range(UnsafeMutableBufferPointer(rebasing: a[left..<n]))
    blit_reverse_range(a)
}

/// Lower bound: first index `i` in `hay` with `hay[i] >= needle`.
func blit_lower_bound(_ hay: UnsafeMutableBufferPointer<Int>, _ needle: Int) -> Int {
    var lo = 0
    var hi = hay.count
    while lo < hi {
        let mid = lo + (hi - lo) / 2
        if hay[mid] < needle {
            lo = mid + 1
        } else {
            hi = mid
        }
    }
    return lo
}

func blit_merge_with_swap(
    _ a: UnsafeMutableBufferPointer<Int>,
    _ mid: Int,
    _ swap: UnsafeMutableBufferPointer<Int>
) {
    let n = a.count
    for i in 0..<mid {
        swap[i] = a[i]
    }
    var i = 0
    var j = mid
    var k = 0
    while i < mid && j < n {
        if swap[i] <= a[j] {
            a[k] = swap[i]
            i += 1
        } else {
            a[k] = a[j]
            j += 1
        }
        k += 1
    }
    while i < mid {
        a[k] = swap[i]
        i += 1
        k += 1
    }
}

/// Merge two adjacent sorted runs `[0..left_len)` and `[left_len..left_len+right_len)`
/// by rotating around the left run's center until the pieces fit in `swap`.
func blit_rotate_merge_block(
    _ a: UnsafeMutableBufferPointer<Int>,
    _ left_len: Int,
    _ right_len: Int,
    _ swap: UnsafeMutableBufferPointer<Int>
) {
    if left_len == 0 || right_len == 0 {
        return
    }
    if a[left_len - 1] <= a[left_len] {
        return
    }

    let total = left_len + right_len
    let swap_cap = swap.count
    if total <= swap_cap {
        blit_merge_with_swap(a, left_len, swap)
        return
    }
    if left_len <= swap_cap {
        blit_merge_with_swap(a, left_len, swap)
        return
    }
    if right_len <= swap_cap {
        // Partial backward merge: right run fits in swap.
        for i in 0..<right_len {
            swap[i] = a[left_len + i]
        }
        var i = left_len
        var j = right_len
        var k = total
        while i > 0 && j > 0 {
            if a[i - 1] > swap[j - 1] {
                k -= 1
                i -= 1
                a[k] = a[i]
            } else {
                k -= 1
                j -= 1
                a[k] = swap[j]
            }
        }
        while j > 0 {
            k -= 1
            j -= 1
            a[k] = swap[j]
        }
        return
    }

    let rblock = left_len / 2
    let lblock = left_len - rblock
    let center = a[lblock]
    let left = blit_lower_bound(UnsafeMutableBufferPointer(rebasing: a[left_len..<total]), center)
    let right = right_len - left

    // Layout: [ lblock | rblock | left | right ]
    if left > 0 {
        blit_rotate(
            UnsafeMutableBufferPointer(rebasing: a[lblock..<(lblock + rblock + left)]),
            rblock,
            swap
        )
        // Now: [ lblock | left | rblock | right ]
        blit_rotate_merge_block(a, lblock, left, swap)
        blit_rotate_merge_block(
            UnsafeMutableBufferPointer(rebasing: a[(lblock + left)..<total]),
            rblock,
            right,
            swap
        )
    } else if right > 0 {
        blit_rotate_merge_block(
            UnsafeMutableBufferPointer(rebasing: a[lblock..<total]),
            rblock,
            right,
            swap
        )
    }
}

func blit_rotate_mergesort(_ a: UnsafeMutableBufferPointer<Int>, _ swap: UnsafeMutableBufferPointer<Int>) {
    let n = a.count
    if n <= 1 {
        return
    }
    let block0 = max(min(BLIT_OUT, swap.count), 1)
    var i = 0
    while i < n {
        let end = min(i + block0, n)
        insertion_sort(UnsafeMutableBufferPointer(rebasing: a[i..<end]))
        i = end
    }
    var block = block0
    while block < n {
        var start = 0
        while start < n {
            let mid = start + block
            if mid >= n {
                break
            }
            let end = min(mid + block, n)
            let left_len = mid - start
            let right_len = end - mid
            blit_rotate_merge_block(
                UnsafeMutableBufferPointer(rebasing: a[start..<end]),
                left_len,
                right_len,
                swap
            )
            start = end
        }
        if block > Int.max / 2 {
            break
        }
        block *= 2
        if block == 0 {
            break
        }
    }
}

/// Stable partition: keys `<= pivot` stay toward the front.
/// When the range exceeds the swap, recurse on halves and rotate the middle
/// so left parts gather contiguously (rotate quicksort's assembly step).
func blit_stable_partition(
    _ a: UnsafeMutableBufferPointer<Int>,
    _ swap: UnsafeMutableBufferPointer<Int>,
    _ pivot: Int
) -> Int {
    let n = a.count
    let swap_cap = swap.count
    if n == 0 {
        return 0
    }
    if n > swap_cap {
        let h = n / 2
        let l = blit_stable_partition(UnsafeMutableBufferPointer(rebasing: a[0..<h]), swap, pivot)
        let r = blit_stable_partition(UnsafeMutableBufferPointer(rebasing: a[h..<n]), swap, pivot)
        // Middle band `a[l..h]` holds the right half of the left partition
        // (`> pivot`); length `h - l`. Right partition contributed `r` left keys
        // at `a[h..h+r]`. Rotate that band of length `(h - l) + r` by `h - l`.
        blit_rotate(UnsafeMutableBufferPointer(rebasing: a[l..<(h + r)]), h - l, swap)
        return l + r
    }

    for i in 0..<n {
        swap[i] = a[i]
    }
    var left = 0
    for i in 0..<n {
        if swap[i] <= pivot {
            left += 1
        }
    }
    var l = 0
    var r = left
    for i in 0..<n {
        let x = swap[i]
        if x <= pivot {
            a[l] = x
            l += 1
        } else {
            a[r] = x
            r += 1
        }
    }
    return left
}

/// Like `blit_stable_partition`, but left keys are strictly less than `pivot`.
/// Used for the equal-key second sweep so ranges larger than the fixed swap
/// still stay within that buffer via half-recursion and rotate.
func blit_strict_partition(
    _ a: UnsafeMutableBufferPointer<Int>,
    _ swap: UnsafeMutableBufferPointer<Int>,
    _ pivot: Int
) -> Int {
    let n = a.count
    let swap_cap = swap.count
    if n == 0 {
        return 0
    }
    if n > swap_cap {
        let h = n / 2
        let l = blit_strict_partition(UnsafeMutableBufferPointer(rebasing: a[0..<h]), swap, pivot)
        let r = blit_strict_partition(UnsafeMutableBufferPointer(rebasing: a[h..<n]), swap, pivot)
        blit_rotate(UnsafeMutableBufferPointer(rebasing: a[l..<(h + r)]), h - l, swap)
        return l + r
    }

    for i in 0..<n {
        swap[i] = a[i]
    }
    var left = 0
    for i in 0..<n {
        if swap[i] < pivot {
            left += 1
        }
    }
    var l = 0
    var r = left
    for i in 0..<n {
        let x = swap[i]
        if x < pivot {
            a[l] = x
            l += 1
        } else {
            a[r] = x
            r += 1
        }
    }
    return left
}

func blit_partition_sort(_ a: UnsafeMutableBufferPointer<Int>, _ swap: UnsafeMutableBufferPointer<Int>) {
    let n = a.count
    if n <= 1 {
        return
    }
    if n <= BLIT_OUT {
        insertion_sort(a)
        return
    }

    let pivot = blit_quasimedian9(a)
    let left = blit_stable_partition(a, swap, pivot)
    let right = n - left

    if right == 0 {
        // Second sweep: gather keys strictly less than pivot. When `n` exceeds
        // the fixed swap, recurse + rotate instead of copying the whole range.
        let lt = blit_strict_partition(a, swap, pivot)
        if lt > 1 {
            blit_partition_sort(UnsafeMutableBufferPointer(rebasing: a[0..<lt]), swap)
        }
        return
    }

    let unbalanced = (left > 0 && left < n / 16) || (right > 0 && right < n / 16)
    if unbalanced {
        if left > 1 {
            blit_rotate_mergesort(UnsafeMutableBufferPointer(rebasing: a[0..<left]), swap)
        }
        if right > 1 {
            blit_rotate_mergesort(UnsafeMutableBufferPointer(rebasing: a[left..<n]), swap)
        }
        return
    }

    if left > 1 {
        blit_partition_sort(UnsafeMutableBufferPointer(rebasing: a[0..<left]), swap)
    }
    if right > 1 {
        blit_partition_sort(UnsafeMutableBufferPointer(rebasing: a[left..<n]), swap)
    }
}

func blit_analyze(_ a: UnsafeMutableBufferPointer<Int>, _ swap: UnsafeMutableBufferPointer<Int>) -> Bool {
    let n = a.count
    if n <= 1 {
        return true
    }
    if blit_is_sorted(a) {
        return true
    }
    if blit_is_reverse_sorted(a) {
        blit_reverse(a)
        return true
    }

    // Four-segment presortedness (flux / blit analyzer stand-in): finish
    // mostly-ordered quarters with rotate mergesort, then fall through to
    // rotate quicksort for remaining disorder.
    let q = n / 4
    if q >= 2 {
        let bounds = [0, q, q * 2, q * 3, n]
        for s in 0..<4 {
            let lo = bounds[s]
            let hi = bounds[s + 1]
            if hi - lo < 2 {
                continue
            }
            let pairs = hi - lo - 1
            if blit_ordered_pairs(UnsafeMutableBufferPointer(rebasing: a[lo..<hi])) * 2 > pairs {
                blit_rotate_mergesort(UnsafeMutableBufferPointer(rebasing: a[lo..<hi]), swap)
            }
        }
        if blit_is_sorted(a) {
            return true
        }
    }
    return false
}

func blit_sort(_ a: inout [Int]) {
    a.withUnsafeMutableBufferPointer { blit_sort($0) }
}

func blit_sort(_ a: UnsafeMutableBufferPointer<Int>) {
    let n = a.count
    if n <= 1 {
        return
    }
    if n <= BLIT_OUT {
        insertion_sort(a)
        return
    }
    let swap_len = min(BLIT_SWAP, n)
    var swap = Array(repeating: 0, count: swap_len)
    let done = swap.withUnsafeMutableBufferPointer { swapBuf -> Bool in
        blit_analyze(a, swapBuf)
    }
    if done {
        return
    }
    swap.withUnsafeMutableBufferPointer { swapBuf in
        blit_partition_sort(a, swapBuf)
    }
}


func benchmark_sort(_ array: inout [Int]) {

    blit_sort(&array)

}

func is_non_decreasing(_ a: [Int]) -> Bool {
    guard a.count >= 2 else { return true }
    for i in 1..<a.count {
        if a[i - 1] > a[i] { return false }
    }
    return true
}

func same_multiset(_ a: [Int], _ b: [Int]) -> Bool {
    if a.count != b.count {
        return false
    }

    var left = a
    var right = b
    left.sort()
    right.sort()
    return left == right
}

func check_correctness_case(_ label: String, _ input: [Int]) {
    var input = input
    let original = input

    benchmark_sort(&input)

    if !is_non_decreasing(input) {
        fatalError("correctness case \(label): output is not sorted")
    }

    if !same_multiset(input, original) {
        fatalError("correctness case \(label): elements were lost or added")
    }
}

// Skip cases larger than the algorithm's measured size cap (MAX_POWER). That
// cap exists because larger inputs are impractically slow; forcing them here
// would stall the published measurement script before any table rows print.
func check_correctness_case_within_limit(_ label: String, _ input: [Int]) {
    if input.count > (1 << MAX_POWER) {
        return
    }
    check_correctness_case(label, input)
}

func few_unique_values(_ size: Int, _ unique: Int, _ seed: UInt64) -> [Int] {
    var state = seed
    var result = [Int]()
    result.reserveCapacity(size)
    for _ in 0..<size {
        state ^= state << 13
        state ^= state >> 7
        state ^= state << 17
        result.append(Int(state % UInt64(unique)) + 1)
    }
    return result
}

func run_correctness_checks() {
    check_correctness_case("empty", [])
    check_correctness_case("single", [42])
    check_correctness_case("duplicates", [3, 1, 3, 2, 1, 2])
    check_correctness_case("sorted", [1, 2, 3, 4, 5])
    check_correctness_case("reverse", [5, 4, 3, 2, 1])
    check_correctness_case("all_equal", [7, 7, 7, 7])
    check_correctness_case("skewed_range", [1_000_000, 2, 1_000_001, 1, 999_999])
    // Static-buffer Grail skips the in-buffer build when key collection is sparse
    // (ideal_buffer = false). Exercising that path catches regressions in buffer gating.
    check_correctness_case(
        "few_keys_len16",
        [2, 2, 2, 2, 2, 2, 2, 2, 4, 3, 1, 2, 3, 4, 1, 4]
    )
    // Seed 0 is a fixed point of the xorshift below, so it would degenerate into
    // yet another all-equal case instead of a 4-value mix. Start at 1.
    for seed in 1...32 {
        check_correctness_case(
            "few_keys_len32_seed_\(seed)",
            few_unique_values(32, 4, UInt64(seed))
        )
    }
    // Small-input cutoffs (insertion sort below 32 elements, etc.) hide duplicate-key
    // bugs in the recursive path, so repeat the duplicate cases at the smallest
    // benchmark size, which every algorithm must handle within reasonable time.
    check_correctness_case("all_equal_len256", [Int](repeating: 7, count: 256))
    for seed in 1...4 {
        check_correctness_case(
            "few_keys_len256_seed_\(seed)",
            few_unique_values(256, 4, UInt64(seed))
        )
    }
    // Blit's equal-key second sweep used to copy the whole range into a fixed
    // 512-element swap; lengths above that must still sort without panicking.
    // Respect MAX_POWER so algorithms with a low measured-size cap (slow,
    // sleep) do not hang here for minutes or months.
    check_correctness_case_within_limit("all_equal_len600", [Int](repeating: 7, count: 600))
    for seed in 1...4 {
        check_correctness_case_within_limit(
            "few_keys_len2048_seed_\(seed)",
            few_unique_values(2048, 4, UInt64(seed))
        )
    }
}


func shuffled(_ size: Int, seed: UInt64) -> [Int] {
    guard size > 0 else { return [] }

    var v = Array(1...size)
    var state = seed

    if size > 1 {
        for i in stride(from: size - 1, through: 1, by: -1) {
            state ^= state << 13
            state ^= state >> 7
            state ^= state << 17

            let j = Int(state % UInt64(i + 1))
            v.swapAt(i, j)
        }
    }

    return v
}

func micros(_ d: Duration) -> UInt64 {
    let c = d.components
    let fromSeconds = UInt64(c.seconds) * 1_000_000
    let fromAttos = UInt64(max(0, c.attoseconds / 1_000_000_000_000))
    return fromSeconds + fromAttos
}

func padLeft(_ value: String, _ width: Int) -> String {
    if value.count >= width {
        return value
    }
    return String(repeating: " ", count: width - value.count) + value
}

func formatSeconds(_ micros: UInt64) -> String {
    let whole = micros / 1_000_000
    let frac = micros % 1_000_000
    let fracStr = padLeft(String(frac), 6).replacingOccurrences(of: " ", with: "0")
    return "\(whole).\(fracStr)"
}

func input_array(_ size: Int, seed: UInt64) -> [Int] {
    shuffled(size, seed: seed)
}

/// Peak heap growth during `benchmark_sort`, in bytes (explicit buffers such as swap).
/// Kept in bytes so the parent can average before rounding; converting to KiB here
/// would truncate sub-KiB buffers to 0 in every run and hide them from the average.
func run_once(size: Int, seed: Int) -> (UInt64, Int) {
    var array = input_array(size, seed: UInt64(seed))

    let baseBytes = alloc_track_live()
    alloc_track_reset_peak()

    let start = ContinuousClock.now

    benchmark_sort(&array)

    let elapsed = ContinuousClock.now - start
    let peakBytes = alloc_track_peak()
    let auxBytes = max(0, peakBytes - baseBytes)

    let expected: [Int] = size > 0 ? Array(1...size) : []
    if array != expected {
        fatalError("sort failed with seed \(seed) for size \(size)")
    }

    return (micros(elapsed), auxBytes)
}

func run_child(_ args: [String]) {
    let size = Int(args[2])!
    let seed = Int(args[3])!
    let (elapsedUs, mem) = run_once(size: size, seed: seed)
    print("\(elapsedUs) \(mem)")
}

let args = CommandLine.arguments
if args.count > 1 && args[1] == "--run-once" {
    run_child(args)
} else {
    run_correctness_checks()

    let tableHeader =
        "| \(padLeft("Size", 10)) | " +
        "\(padLeft("Average time (s)", 16)) | " +
        "\(padLeft("Maximum time (s)", 16)) | " +
        "\(padLeft("Average memory (KiB)", 20)) | " +
        "\(padLeft("Maximum memory (KiB)", 20)) |"
    print(tableHeader)
    print("|-----------:|-----------------:|-----------------:|---------------------:|---------------------:|")

    for power in MIN_POWER...MAX_POWER {
        let size = 1 << power

        var totalTime: UInt64 = 0
        var maxTime: UInt64 = 0

        var totalMem = 0
        var maxMem = 0

        for seed in 1...RUNS {
            let process = Process()
            process.executableURL = URL(fileURLWithPath: args[0])
            process.arguments = ["--run-once", "\(size)", "\(seed)"]
            let stdout = Pipe()
            let stderr = Pipe()
            process.standardOutput = stdout
            process.standardError = stderr

            do {
                try process.run()
            } catch {
                fatalError("failed to run benchmark child process: \(error)")
            }
            process.waitUntilExit()

            if process.terminationStatus != 0 {
                let err = String(data: stderr.fileHandleForReading.readDataToEndOfFile(), encoding: .utf8) ?? ""
                fatalError("benchmark child process failed: \(err)")
            }

            let data = stdout.fileHandleForReading.readDataToEndOfFile()
            let stdoutText = String(data: data, encoding: .utf8) ?? ""
            let fields = stdoutText.split(whereSeparator: \.isWhitespace)
            guard fields.count >= 2,
                  let elapsedUs = UInt64(fields[0]),
                  let auxMem = Int(fields[1]) else {
                fatalError("invalid child process output: \(stdoutText)")
            }

            totalTime += elapsedUs
            if elapsedUs > maxTime {
                maxTime = elapsedUs
            }

            totalMem += auxMem
            if auxMem > maxMem {
                maxMem = auxMem
            }
        }

        let avgTime = totalTime / UInt64(RUNS)
        // Memory is summed in bytes and converted to KiB once, after averaging.
        let avgMemKb = totalMem / RUNS / 1024
        let maxMemKb = maxMem / 1024

        let tableRow =
            "| \(padLeft(String(size), 10)) | " +
            "\(padLeft(formatSeconds(avgTime), 16)) | " +
            "\(padLeft(formatSeconds(maxTime), 16)) | " +
            "\(padLeft(String(avgMemKb), 20)) | " +
            "\(padLeft(String(maxMemKb), 20)) |"
        print(tableRow)
    }
}
SWIFT

RUN clang -O2 -fPIC -shared alloc_track.c -o liballoc_track.so -ldl

RUN swiftc -Ounchecked -whole-module-optimization \
    main.swift \
    -o swift-benchmark \
    -L. -lalloc_track \
    -Xlinker -rpath -Xlinker /app

ENV LD_PRELOAD=/app/liballoc_track.so
CMD ["./swift-benchmark"]
"""#
    try dockerfile.write(
        to: workdir.appendingPathComponent("Dockerfile"),
        atomically: true,
        encoding: .utf8
    )

    // Keeping build and run as separate child processes preserves Docker's
    // normal output and the original image tag used by the benchmark skill.
    try runCommand("docker", ["build", "-t", "swift-benchmark", workdir.path])
    try runCommand("docker", ["run", "--rm", "--init", "swift-benchmark"])
} catch {
    fputs("\(error)\n", stderr)
    exit(1)
}