sort_unstable_by_key Ranks Records By Field

Order records with sort_unstable_by_key using a cheap extracted key, and compare it with sort_by_key to see that unstable sorting does not preserve ties.

RustData Integrity

Code

rustsnippet
30 lines
#[derive(Debug, Clone)]
struct Job {
    name: &'static str,
    priority: u8,
}

fn main() {
    let mut jobs = vec![
        Job { name: "email", priority: 2 },
        Job { name: "report", priority: 1 },
        Job { name: "cleanup", priority: 2 },
        Job { name: "billing", priority: 1 },
    ];

    // unstable 版按 key 排序,不保证同 priority 的相对顺序
    jobs.sort_unstable_by_key(|job| job.priority);
    for job in &jobs {
        println!("{}: priority {}", job.name, job.priority);
    }

    // 与 stable 版本对照:同 key 的输入顺序被保留
    let mut stable = vec![
        Job { name: "email", priority: 2 },
        Job { name: "report", priority: 1 },
        Job { name: "cleanup", priority: 2 },
        Job { name: "billing", priority: 1 },
    ];
    stable.sort_by_key(|job| job.priority);
    println!("stable ties: {:?}", stable.iter().map(|j| j.name).collect::<Vec<_>>());
}

What the code does

sort_unstable_by_key Ranks Records By Field comes down to the function main.

One loop does the cycling here: for job in &jobs.

Watch out for

  • Self-contained — no imports beyond what the runtime already provides.

Applying it

The main signature reads fn main()

The file announces its steps in the output: stable ties:.

Statements that matter

jobs.sort_unstable_by_key(|job| job.priority);
stable.sort_by_key(|job| job.priority);

Interactive Tools for This Topic

FAQ

What does sort_unstable_by_key Ranks Records By Field print when run?
Execute the whole file; each printed line is prefixed with a label like `stable ties:`.