Is Sorted Validates Ordered Input

is_sorted checks ascending order under PartialOrd and is_sorted_by_key validates a key such as a timestamp stays monotonic before the data is trusted.

RustData Integrity

Code

rustsnippet
18 lines
fn main() {
    let ascending = [1, 3, 3, 7];
    let descending = [9, 5, 5, 1];
    let shuffled = [4, 1, 3];

    // is_sorted:按 PartialOrd 检查升序(非严格,允许相邻相等)
    println!("ascending: {}", ascending.is_sorted());
    println!("descending: {}", descending.is_sorted());
    println!("shuffled: {}", shuffled.is_sorted());

    // is_sorted_by_key:按键函数校验,比如事件序号必须单调递增
    let events = [(1, "boot"), (2, "ready"), (5, "serve")];
    println!("events ordered: {}", events.is_sorted_by_key(|e| e.0));

    // 校验失败时调用方决定拒绝,而不是静默处理乱序数据
    let bad = [(1, "a"), (0, "b")];
    println!("bad ordered: {}", bad.is_sorted_by_key(|e| e.0));
}

How it works

Count the function main as the entire surface area of Is Sorted Validates Ordered Input.

Putting it to use

The demo output is labeled (ascending:, descending:, shuffled:), so every printed line maps back to its originating operation.

Core lines

let events = [(1, "boot"), (2, "ready"), (5, "serve")];
let bad = [(1, "a"), (0, "b")];
let descending = [9, 5, 5, 1];

Interactive Tools for This Topic

FAQ

What does Is Sorted Validates Ordered Input print when run?
Running the file directly is enough — expect labeled output lines such as `ascending:`, `descending:`, `shuffled:`.