75. select_nth_unstable — Find the Kth Element Without Sorting
You’re sorting an entire Vec just to grab the median or the top 3 elements. select_nth_unstable does it in O(n) — no full sort required.
The classic approach: sort everything, then index:
| |
That’s O(n log n) to answer an O(n) question. select_nth_unstable uses a partial-sort algorithm (quickselect) to put the element at a given index into its final sorted position — everything before it is smaller or equal, everything after is greater or equal:
| |
The method returns three mutable slices — elements below, the pivot element, and elements above — so you can work with each partition directly:
| |
Need the top 3 scores without sorting the full list? Select the boundary, then sort only the small tail:
| |
Custom ordering works too. Find the median by absolute value:
| |
The “unstable” in the name means equal elements might be reordered (like sort_unstable) — it doesn’t mean the API is experimental. This is stable since Rust 1.49, available on any [T] where T: Ord.