Logo

dev-resources.site

for different kinds of informations.

Reversing sort order in Rust

Published at
11/21/2023
Categories
rust
sorting
sources
algorithms
Author
rsk
Categories
4 categories in total
rust
open
sorting
open
sources
open
algorithms
open
Author
3 person written this
rsk
open
Reversing sort order in Rust

Rust allows sort items by key easily with .sort_by_key, here is example, it will put important notes to the end:

#[derive(Debug)]
struct Note {
    important: bool,
    title: &'static str,
}
let mut notes = vec![
    Note { important: false, title: "ddd"},
    Note { important: true, title: "aaa"},
    Note { important: false, title: "ccc"},
];
notes.sort_by_key(|k| k.important);
println!("{:?}", notes);
Enter fullscreen mode Exit fullscreen mode

But reversing order of sorting with key may be not so obvious, it is achieved with Reverse helper struct, here is how it can be applied to above example, in order to put important notes first:

use std::cmp::Reverse;
// ...
notes.sort_by_key(|k| Reverse(k.important));
println!("{:?}", notes);
Enter fullscreen mode Exit fullscreen mode

How is it implemented? Let's look at the source code of Rust standard library:

pub struct Reverse<T>(pub T);

impl<T: Ord> Ord for Reverse<T> {
    fn cmp(&self, other: &Reverse<T>) -> Ordering {
        other.0.cmp(&self.0)
    }
}
Enter fullscreen mode Exit fullscreen mode

The implementation is straightforward, it is newtype wrapper for original type, and for types with Ord trait it reimplements Ord but instead of comparing self with other it comparing other with self meaning it will reverse order in the result. Simple and beautiful!

And it will play nicely with complex keys too, lets put important notes first, and sort by title ascending for same importance groups:

notes.sort_by_key(|k| (Reverse(k.important), k.title));
println!("{:?}", notes);
Enter fullscreen mode Exit fullscreen mode

Of course in some cases it is possible to just negate value, like in this example using !k.important will produce same results, but negating is not always possible (eg. strings). Regarding performance I've benchmarked both methods and have not found any difference, both methods require same time if ordering booleans.

My links

I'm making my perfect todo, note-taking app Heaplist, you can try it here heaplist.app
I have a twitter @rsk
And a website rsk

sorting Article's
30 articles in total
Favicon
Difference Between Merge Sort and Quick Sort
Favicon
Leetcode 75. Sort Colors
Favicon
Sorted Data Structures in Python
Favicon
Sorting Algorithms That Use Hash Tables
Favicon
C# Essentials: Operator Overloading and Custom Sorting Made Simple
Favicon
Recap the highlight of the sorting algorithms using JavaScript for beginners
Favicon
Merge Sort Demystified: A Beginner's Guide to Divide and Conquer Sorting
Favicon
Understanding Bubble Sort: Simple Sorting Method
Favicon
Introduction to Sorting Algorithms in JavaScript
Favicon
Understanding the SQL ORDER BY Clause
Favicon
Demystifying Sorting Algorithms: Making Order Out of Chaos
Favicon
Merge Intervals : A unique Graph-based approach
Favicon
Bubble Sort
Favicon
COMPARATOR vs COMPARABLEโ€Š-โ€ŠA Java Surprise You did inย School!
Favicon
Streamlining Data Management with Python's sorted() Function
Favicon
1 billion rows challenge in MySQL
Favicon
1 billion rows challenge in PostgreSQL and ClickHouse
Favicon
Sorting in Java โ€“ how to, and how not to do it anymore
Favicon
Reversing sort order in Rust
Favicon
Priority Queue: Creating order from chaos
Favicon
Mastering Array Sorting in PHP: usort & uasort ๐Ÿš€๐Ÿš€
Favicon
QuickSort - Time Analysis (Part2)
Favicon
Quicksort (Grokking Algorithms)
Favicon
Better Bogo Sort
Favicon
Sorting Array of Objects in Javascript
Favicon
Bubble Sort
Favicon
Understanding insertion sort algorithm
Favicon
Sorting Visualizer [ A web app to visualize sorting algorithm ]
Favicon
How to sort complex objects with custom criteria in Python
Favicon
Iterative Sorting algorithms in Javascript

Featured ones: