partition_point Finds Sorted Boundary

Locate the first element failing a predicate in sorted data with partition_point, replacing hand-written binary search loops.

RustResilience

Code

rustsnippet
19 lines
fn main() {
    let latencies_ms = [3, 9, 12, 18, 25, 31, 44];

    // partition_point:有序序列中第一个让谓词返回 false 的下标
    // partition_point finds the boundary in sorted data
    let first_slow = latencies_ms.partition_point(|&ms| ms < 20);
    println!(
        "first >= 20ms: index {} value {}",
        first_slow, latencies_ms[first_slow]
    );
    println!("slow tail: {:?}", &latencies_ms[first_slow..]);

    // 谓词必须单调:前面全 true,后面全 false
    let within_budget = latencies_ms.partition_point(|&ms| ms <= 30);
    println!("{} samples within 30ms", within_budget);

    let empty: [u32; 0] = [];
    println!("empty boundary: {}", empty.partition_point(|_| true));
}

What the code does

partition_point Finds Sorted Boundary keeps everything in the function main.

Applying it

Running the file prints labeled results such as first >= 20ms: index, slow tail:, empty boundary: — each operation’s effect is visible in the output.

Statements that matter

let within_budget = latencies_ms.partition_point(|&ms| ms <= 30);
let first_slow = latencies_ms.partition_point(|&ms| ms < 20);
let latencies_ms = [3, 9, 12, 18, 25, 31, 44];

Interactive Tools for This Topic

FAQ

What does partition_point Finds Sorted Boundary print when run?
Run it as a complete program — the output lines carry labels such as `first >= 20ms: index`, `slow tail:`, `empty boundary:`.