ドロップマージソートを使用する

ドロップマージソート (drop-merge sort) は、ほぼ整列済みの入力向けに提案された適応的な不安定ソートである。

損失ソートとして知られるドロップソート(順序を崩す要素を捨てる)を「より多くの要素を残す」方向へ改良した近似的な最長非減少部分列(LNS)検出を土台にし、捨てた要素を別途ソートして戻しマージする。

整列済みリストへ少数の変更を加えたあと再ソートする、といった「大半がすでに昇順で、外れ値が散在する」場面で特に効く。N 個中 K 個が外れ値なら、比較回数の目安は \(O(N + K \log K)\)、追加メモリは \(O(K)\) である。

  1. 最長非減少部分列の近似抽出: 配列を左から走査し、直前に残した末尾以上ならその場へ詰めて残す。末尾より小さければいったん「ドロップ」(別リストへ退避)する。
  2. 誤採択の取り消し: 連続ドロップが閾値(本稿では 8)に達したら、直前に残した要素が外れ値だったとみなし、その要素と必要ならさらに手前までをドロップへ戻して読み位置を巻き戻す。直前 1 件だけが跳ね上がっている典型例は、連続ドロップ前の「1 つ手前との二重比較」で即時に取り消す。
  3. 早期打ち切り: 走査の早い段階でドロップ率が高すぎるときは、ほぼ乱順と判断して配列全体をクイックソートへ委ねる。
  4. マージ: 残した非減少列と、ソート済みのドロップ列を末尾側からマージして元配列へ書き戻す。
procedure drop_merge_sort(A)
  n = length(A)
  if n < 2 then
    return
  dropped = empty list
  write = 0
  read = 0
  num_dropped_in_row = 0
  while read < n
    if write == 0 or A[read] >= A[write - 1] then
      A[write] = A[read]
      write = write + 1
      read = read + 1
      num_dropped_in_row = 0
    else if num_dropped_in_row == 0 and write >= 2
         and A[read] >= A[write - 2] then
      append A[write - 1] to dropped
      A[write - 1] = A[read]
      read = read + 1
    else if num_dropped_in_row < RECENCY then
      append A[read] to dropped
      read = read + 1
      num_dropped_in_row = num_dropped_in_row + 1
    else
      undo last num_dropped_in_row drops
      backtrack write until a recently seen value can stay
      append backtracked values to dropped
      num_dropped_in_row = 0
  sort(dropped)  // e.g. quicksort
  merge A[0 .. write) and dropped into A from the right

ほぼ整列済みなら \(K\) が小さく高速になる一方、乱順では早期打ち切り後のクイックソート相当になる。マージは同値の扱いを固定しないため不安定である。

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

ナチュラルマージソートは隣接する自然ランをそのままマージするのに対し、ドロップマージは「1 本の長い非減少列をできるだけ残し、外れ値だけを別処理する」点が違う。ラン境界で切らず、飛び飛びの最長非減少部分列近似を取る。

ストランドソートも非減少部分列を抜き出してマージするが、毎回先頭からストランドを取り、残りは次ラウンドへ回す。ドロップマージは 1 回の走査で最長非減少部分列近似を固め、ドロップ側をまとめてソートしてから 1 度マージする。

ティムソートパワーソートは自然ランの検出に加え、短いランの拡張やスタック制約など実用向けの制御が多い。ドロップマージは「ほぼ整列+散在する外れ値」に特化した単純なハイブリッドである。

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

Size Average time (s) Maximum time (s) Average memory (KiB) Maximum memory (KiB)
256 0.000014 0.000181 0 0
512 0.000025 0.001978 1 1
1024 0.000048 0.000462 2 3
2048 0.000095 0.000649 5 6
4096 0.000197 0.000959 11 12
8192 0.000414 0.003557 24 24
16384 0.000796 0.009861 48 48
32768 0.001192 0.009827 96 96
65536 0.003016 0.019173 196 196
131072 0.007691 0.014485 395 395
262144 0.014065 0.030691 791 791
計測に使用したコードを表示する

#!/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
        }
    }
}

func partition_at(_ a: UnsafeMutableBufferPointer<Int>, _ lo: Int, _ hi: Int, _ pivot_idx: Int) -> Int {
    a.swapAt(pivot_idx, hi)
    let pivot = a[hi]
    var i = lo
    for j in lo..<hi {
        if a[j] < pivot {
            a.swapAt(i, j)
            i += 1
        }
    }
    a.swapAt(i, hi)
    return i
}

func partition(_ a: UnsafeMutableBufferPointer<Int>, _ lo: Int, _ hi: Int) -> Int {
    partition_at(a, lo, hi, lo + (hi - lo) / 2)
}

func quick_sort_range(_ a: UnsafeMutableBufferPointer<Int>, _ lo: Int, _ hi: Int) {
    if hi <= lo {
        return
    }
    if hi - lo < 16 {
        insertion_sort(UnsafeMutableBufferPointer(rebasing: a[lo..<(hi + 1)]))
        return
    }
    let p = partition(a, lo, hi)
    if p > 0 {
        quick_sort_range(a, lo, p - 1)
    }
    quick_sort_range(a, p + 1, hi)
}

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

func quick_sort(_ a: UnsafeMutableBufferPointer<Int>) {
    if a.count > 0 {
        let hi = a.count - 1
        quick_sort_range(a, 0, hi)
    }
}



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

func drop_merge_sort(_ a: UnsafeMutableBufferPointer<Int>) {
    let n = a.count
    if n < 2 {
        return
    }

    let recency = 8
    let earlyOutTestAt = 4
    let earlyOutDisorderFraction = 0.60

    var dropped = [Int]()
    var numDroppedInRow = 0
    var write = 0
    var read = 0
    var iteration = 0
    let earlyOutStop = n / earlyOutTestAt

    while read < n {
        iteration += 1
        if iteration == earlyOutStop
            && Double(dropped.count) > Double(read) * earlyOutDisorderFraction
        {
            for i in 0..<dropped.count {
                a[write + i] = dropped[i]
            }
            quick_sort(a)
            return
        }

        if write == 0 || a[read] >= a[write - 1] {
            if read != write {
                a[write] = a[read]
            }
            read += 1
            write += 1
            numDroppedInRow = 0
        } else {
            if numDroppedInRow == 0
                && write >= 2
                && a[read] >= a[write - 2]
            {
                dropped.append(a[write - 1])
                a[write - 1] = a[read]
                read += 1
                continue
            }

            if numDroppedInRow < recency {
                dropped.append(a[read])
                read += 1
                numDroppedInRow += 1
            } else {
                dropped.removeLast(numDroppedInRow)
                read -= numDroppedInRow

                var numBacktracked = 1
                write -= 1

                var maxOfDropped = a[read]
                for i in 1...(numDroppedInRow) {
                    let v = a[read + i]
                    if v > maxOfDropped {
                        maxOfDropped = v
                    }
                }
                while write >= 1 && maxOfDropped < a[write - 1] {
                    numBacktracked += 1
                    write -= 1
                }

                for i in 0..<numBacktracked {
                    dropped.append(a[write + i])
                }
                numDroppedInRow = 0
            }
        }
    }

    quick_sort(&dropped)

    var back = n
    while let lastDropped = dropped.last {
        while write > 0 && lastDropped < a[write - 1] {
            a[back - 1] = a[write - 1]
            back -= 1
            write -= 1
        }
        a[back - 1] = lastDropped
        back -= 1
        dropped.removeLast()
    }
}


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

    drop_merge_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)
}