スプレイソートを使用する

スプレイソート (splay sort) は、要素を順にスプレイ木へ挿入し、中順走査ですべてのキーを読み出して昇順にする。

スプレイ木は、参照したノードを根へ持ち上げる(スプレイ操作)自己調整二分探索木であり、直近にアクセスした要素へ素早く再び到達できる。

  1. 挿入: 入力値を順にスプレイ木へ挿入する。各挿入のあと、挿入したキー(または探索経路上の最終ノード)が根へスプレイされる。
  2. 取出し: 中順走査でキーを昇順に列挙し、配列へ書き込む。
procedure splay_sort(elements)
  T = empty splay tree
  for x in elements
    insert_splay(T, x)
  return inorder_traversal(T)

償却 O(n log n) だが、ノード用に O(n) の追加記憶域が要る(インプレースではない)。

等しいキー同士の相対順序は木の実装や等値を左子・右子のどちらへ入れるかの規約に依存し、一般には安定ソートではない。次のデモでは、同じ値の棒が画面上で入れ替わらないよう、挿入の比較を値が異なれば値、等しければ元の位置 id の辞書式順にしている。これは可視化のための工夫であり、素のスプレイソートが安定であることを意味しない。

procedure insert_splay(T, x)
  if T is empty then
    T.root = new node(x)
    return
  splay(T, x)
  if x = T.root.key then
    increment count at T.root
  else if x < T.root.key then
    attach old left subtree of T.root to new node(x)
    make T.root the right child of new node(x)
    T.root = new node(x)
  else
    attach old right subtree of T.root to new node(x)
    make T.root the left child of new node(x)
    T.root = new node(x)

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

ツリーソートと同様に挿入後に中順走査するが、スプレイ木は触れたノードを根へ回転する。辞書向きの局所性があり、一度きりの全整列では回転コストが重い。

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

Size Average time Maximum time Average memory Maximum memory
256 0.000030 0.000193 10 10
512 0.000065 0.000211 20 20
1024 0.000141 0.000381 40 40
2048 0.000301 0.000595 80 80
4096 0.000636 0.002798 160 160
8192 0.001314 0.004165 320 320
16384 0.003157 0.009412 640 640
32768 0.006954 0.013153 1280 1280
65536 0.016191 0.032203 2560 2560
131072 0.037249 0.119949 5120 5120
262144 0.086755 0.158212 10240 10240
計測に使用したコードを表示する

set -euo pipefail

WORKDIR="$(mktemp -d)"
trap 'rm -rf "$WORKDIR"' EXIT

cat > "$WORKDIR/Dockerfile" <<'EOF'
FROM rust:1.95.0

WORKDIR /app

RUN mkdir -p src

RUN cat > Cargo.toml <<'CARGO'
[package]
name = "rust-benchmark"
version = "0.1.0"
edition = "2021"

[profile.release]
lto = true
codegen-units = 1
panic = "abort"
CARGO

RUN cat > src/main.rs <<'RUST'
use std::{
    alloc::{GlobalAlloc, Layout, System},
    env,
    process::Command,
    sync::atomic::{AtomicUsize, Ordering as AtomicOrdering},
    time::{Duration, Instant},
};

/// Counts live heap bytes and the high-water mark so auxiliary sort buffers
/// (swap Vecs, etc.) are measured as explicit heap growth during the sort.
struct TrackingAllocator;

static LIVE_BYTES: AtomicUsize = AtomicUsize::new(0);
static PEAK_BYTES: AtomicUsize = AtomicUsize::new(0);

fn record_alloc(size: usize) {
    let live = LIVE_BYTES.fetch_add(size, AtomicOrdering::Relaxed) + size;
    PEAK_BYTES.fetch_max(live, AtomicOrdering::Relaxed);
}

unsafe impl GlobalAlloc for TrackingAllocator {
    unsafe fn alloc(&self, layout: Layout) -> *mut u8 {
        let ptr = System.alloc(layout);
        if !ptr.is_null() {
            record_alloc(layout.size());
        }
        ptr
    }

    unsafe fn dealloc(&self, ptr: *mut u8, layout: Layout) {
        LIVE_BYTES.fetch_sub(layout.size(), AtomicOrdering::Relaxed);
        System.dealloc(ptr, layout);
    }

    unsafe fn alloc_zeroed(&self, layout: Layout) -> *mut u8 {
        let ptr = System.alloc_zeroed(layout);
        if !ptr.is_null() {
            record_alloc(layout.size());
        }
        ptr
    }

    unsafe fn realloc(&self, ptr: *mut u8, layout: Layout, new_size: usize) -> *mut u8 {
        let new_ptr = System.realloc(ptr, layout, new_size);
        if !new_ptr.is_null() {
            LIVE_BYTES.fetch_sub(layout.size(), AtomicOrdering::Relaxed);
            record_alloc(new_size);
        }
        new_ptr
    }
}

#[global_allocator]
static GLOBAL: TrackingAllocator = TrackingAllocator;
const MIN_POWER: u32 = 8;
const MAX_POWER: u32 = 18;
const RUNS: usize = 8192;


type Link = Option<Box<Node>>;

#[derive(Default)]
struct Node {
    value: usize,
    count: usize,
    left: Link,
    right: Link,
}

fn rotate_right(mut x: Box<Node>) -> Box<Node> {
    let mut y = x.left.take().expect("rotate_right");
    x.left = y.right.take();
    y.right = Some(x);
    y
}

fn rotate_left(mut x: Box<Node>) -> Box<Node> {
    let mut y = x.right.take().expect("rotate_left");
    x.right = y.left.take();
    y.left = Some(x);
    y
}

fn splay(mut root: Box<Node>, key: usize) -> Box<Node> {
    if key < root.value {
        if let Some(mut left) = root.left.take() {
            if key < left.value {
                if let Some(grand_left) = left.left.take() {
                    left.left = Some(splay(grand_left, key));
                    left = rotate_right(left);
                }
                root.left = Some(left);
                return rotate_right(root);
            }
            if key > left.value {
                left.right = left.right.take().map(|r| splay(r, key));
                if left.right.is_some() {
                    root.left = Some(rotate_left(left));
                    return rotate_right(root);
                }
                root.left = Some(left);
            } else {
                // key == left.value: zig so the match becomes root (for count bumps).
                root.left = Some(left);
                return rotate_right(root);
            }
        }
    } else if key > root.value {
        if let Some(mut right) = root.right.take() {
            if key > right.value {
                if let Some(grand_right) = right.right.take() {
                    right.right = Some(splay(grand_right, key));
                    right = rotate_left(right);
                }
                root.right = Some(right);
                return rotate_left(root);
            }
            if key < right.value {
                right.left = right.left.take().map(|l| splay(l, key));
                if right.left.is_some() {
                    root.right = Some(rotate_right(right));
                    return rotate_left(root);
                }
                root.right = Some(right);
            } else {
                // key == right.value: zig so the match becomes root (for count bumps).
                root.right = Some(right);
                return rotate_left(root);
            }
        }
    }
    root
}

fn splay_insert(root: Link, value: usize) -> Link {
    match root {
        None => Some(Box::new(Node {
            value,
            count: 1,
            left: None,
            right: None,
        })),
        Some(node) => {
            let mut node = splay(node, value);
            if node.value == value {
                node.count += 1;
                return Some(node);
            }
            if value < node.value {
                let mut new_node = Box::new(Node {
                    value,
                    count: 1,
                    left: node.left.take(),
                    right: None,
                });
                new_node.right = Some(node);
                Some(new_node)
            } else {
                let right = node.right.take();
                let mut new_node = Box::new(Node {
                    value,
                    count: 1,
                    left: None,
                    right,
                });
                new_node.left = Some(node);
                Some(new_node)
            }
        }
    }
}

fn drain_node(root: &Link, out: &mut Vec<usize>) {
    if let Some(node) = root {
        drain_node(&node.left, out);
        out.extend(std::iter::repeat(node.value).take(node.count));
        drain_node(&node.right, out);
    }
}

fn splay_sort(a: &mut [usize]) {
    let mut root = None;
    for &value in a.iter() {
        root = splay_insert(root, value);
    }
    let mut out = Vec::with_capacity(a.len());
    drain_node(&root, &mut out);
    a.copy_from_slice(&out);
}


fn benchmark_sort(array: &mut [usize]) {

    splay_sort(array);

}

fn is_non_decreasing(a: &[usize]) -> bool {
    a.windows(2).all(|w| w[0] <= w[1])
}

fn same_multiset(a: &[usize], b: &[usize]) -> bool {
    if a.len() != b.len() {
        return false;
    }

    let mut left = a.to_vec();
    let mut right = b.to_vec();
    left.sort_unstable();
    right.sort_unstable();
    left == right
}

fn check_correctness_case(label: &str, mut input: Vec<usize>) {
    let original = input.clone();

    benchmark_sort(&mut input);

    if !is_non_decreasing(&input) {
        panic!("correctness case {}: output is not sorted", label);
    }

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

fn few_unique_values(size: usize, unique: usize, seed: u64) -> Vec<usize> {
    let mut state = seed;

    (0..size)
        .map(|_| {
            state ^= state << 13;
            state ^= state >> 7;
            state ^= state << 17;
            (state as usize % unique) + 1
        })
        .collect()
}

fn run_correctness_checks() {
    check_correctness_case("empty", vec![]);
    check_correctness_case("single", vec![42]);
    check_correctness_case("duplicates", vec![3, 1, 3, 2, 1, 2]);
    check_correctness_case("sorted", vec![1, 2, 3, 4, 5]);
    check_correctness_case("reverse", vec![5, 4, 3, 2, 1]);
    check_correctness_case("all_equal", vec![7, 7, 7, 7]);
    check_correctness_case("skewed_range", vec![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",
        vec![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(
            &format!("few_keys_len32_seed_{seed}"),
            few_unique_values(32, 4, 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", vec![7; 256]);
    for seed in 1..=4 {
        check_correctness_case(
            &format!("few_keys_len256_seed_{seed}"),
            few_unique_values(256, 4, 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.
    check_correctness_case("all_equal_len600", vec![7; 600]);
    for seed in 1..=4 {
        check_correctness_case(
            &format!("few_keys_len2048_seed_{seed}"),
            few_unique_values(2048, 4, seed),
        );
    }
}


fn shuffled(size: usize, seed: u64) -> Vec<usize> {
    let mut v: Vec<usize> = (1..=size).collect();

    let mut state = seed;

    for i in (1..size).rev() {
        state ^= state << 13;
        state ^= state >> 7;
        state ^= state << 17;

        let j = (state as usize) % (i + 1);

        v.swap(i, j);
    }

    v
}

fn micros(d: Duration) -> u128 {
    d.as_micros()
}

fn input_array(size: usize, seed: u64) -> Vec<usize> {
    shuffled(size, 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.
fn run_once(size: usize, seed: usize) -> (u128, usize) {
    let mut array = input_array(size, seed as u64);

    let base_bytes = LIVE_BYTES.load(AtomicOrdering::Relaxed);
    PEAK_BYTES.store(base_bytes, AtomicOrdering::Relaxed);

    let start = Instant::now();

    benchmark_sort(&mut array);

    let elapsed = start.elapsed();
    let peak_bytes = PEAK_BYTES.load(AtomicOrdering::Relaxed);
    let aux_bytes = peak_bytes.saturating_sub(base_bytes);

    let expected: Vec<usize> = (1..=size).collect();
    if array != expected {
        panic!(
            "sort failed with seed {} for size {}",
            seed,
            size
        );
    }

    (micros(elapsed), aux_bytes)
}

fn run_child(args: &[String]) {
    let size = args[2].parse::<usize>().expect("invalid size");
    let seed = args[3].parse::<usize>().expect("invalid seed");
    let (elapsed_us, mem) = run_once(size, seed);
    println!("{} {}", elapsed_us, mem);
}

fn main() {
    let args: Vec<String> = env::args().collect();
    if args.get(1).is_some_and(|arg| arg == "--run-once") {
        run_child(&args);
        return;
    }

    run_correctness_checks();

    println!(
        "| {:>10} | {:>15} | {:>15} | {:>15} | {:>15} |",
        "Size",
        "Average time",
        "Maximum time",
        "Average memory",
        "Maximum memory"
    );

    println!(
        "|{:-<11}:|{:-<16}:|{:-<16}:|{:-<16}:|{:-<16}:|",
        "",
        "",
        "",
        "",
        ""
    );

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

        let mut total_time: u128 = 0;
        let mut max_time: u128 = 0;

        let mut total_mem: usize = 0;
        let mut max_mem: usize = 0;

        for seed in 1..=RUNS {
            let output = Command::new(env::current_exe().expect("failed to find current executable"))
                .arg("--run-once")
                .arg(size.to_string())
                .arg(seed.to_string())
                .output()
                .expect("failed to run benchmark child process");

            if !output.status.success() {
                panic!(
                    "benchmark child process failed: {}",
                    String::from_utf8_lossy(&output.stderr)
                );
            }

            let stdout = String::from_utf8(output.stdout)
                .expect("child process returned non-UTF-8 output");
            let mut fields = stdout.split_whitespace();
            let elapsed_us = fields
                .next()
                .expect("missing elapsed time")
                .parse::<u128>()
                .expect("invalid elapsed time");
            let aux_mem = fields
                .next()
                .expect("missing memory usage")
                .parse::<usize>()
                .expect("invalid memory usage");

            total_time += elapsed_us;

            if elapsed_us > max_time {
                max_time = elapsed_us;
            }

            total_mem += aux_mem;

            if aux_mem > max_mem {
                max_mem = aux_mem;
            }
        }

        let avg_time = total_time / RUNS as u128;
        // Memory is summed in bytes and converted to KiB once, after averaging.
        let avg_mem_kb = total_mem / RUNS / 1024;
        let max_mem_kb = max_mem / 1024;

        println!(
            "| {:>10} | {:>15} | {:>15} | {:>15} | {:>15} |",
            size,
            format!("{}.{:06}", avg_time / 1_000_000, avg_time % 1_000_000),
            format!("{}.{:06}", max_time / 1_000_000, max_time % 1_000_000),
            avg_mem_kb,
            max_mem_kb
        );
    }
}
RUST

RUN cargo build --release

CMD ["./target/release/rust-benchmark"]
EOF

docker build -t rust-benchmark "$WORKDIR"
docker run --rm --init rust-benchmark