Rs
Module 4Sorting & Custom ComparatorsLesson 14 of 2318 min

Sorting Structs & Argsort

Derive Ord or custom; indices argsort pattern.

Derive Ord

rust
#[derive(Eq, PartialEq, Ord, PartialOrd)]
struct Person { name: String, age: u32 } // field order matters for Ord

Usually better: explicit sort_by_key so intent is clear.

Argsort

rust
let mut idx: Vec<usize> = (0..n).collect();
idx.sort_by_key(|&i| nums[i]);

Keeps original array while knowing ranked order — common in interviews.

Challenge

Argsort nums = [40,10,30,20] and print values in sorted order via indices.

Tips
  • Explicit sort_by_key > surprise Ord
  • Argsort preserves original
  • Stable sort: sort not sort_unstable

Try it live

Sorting Structs & ArgsortRust 2021
Loading editor…
Output
Press Run to compile and execute.