Skip to content

Commit e990665

Browse files
committed
Recipe Series: Sort Vector #437
* Add simple sorting vector of integers * Add sorting of vector of floats * Add sorting of vector of structs by custom natural order * Add sorting of vector of structs by custom comparator
1 parent 7e59e4e commit e990665

File tree

7 files changed

+180
-0
lines changed

7 files changed

+180
-0
lines changed

src/SUMMARY.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,7 @@
44
[About](about.md)
55
- [Algorithms](algorithms.md)
66
- [Generate Random Values](algorithms/randomness.md)
7+
- [Sort a Vector](algorithms/sorting.md)
78
- [Command Line](cli.md)
89
- [Argument Parsing](cli/arguments.md)
910
- [Compression](compression.md)

src/algorithms.md

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -8,12 +8,20 @@
88
| [Generate random values of a custom type][ex-rand-custom] | [![rand-badge]][rand] | [![cat-science-badge]][cat-science] |
99
| [Create random passwords from a set of alphanumeric characters][ex-rand-passwd] | [![rand-badge]][rand] | [![cat-os-badge]][cat-os] |
1010
| [Create random passwords from a set of user-defined characters][ex-rand-choose] | [![rand-badge]][rand] | [![cat-os-badge]][cat-os] |
11+
| [Sort a Vector of Integers][ex-sort-integers] | [![std-badge]][std] | [![cat-science-badge]][cat-science] |
12+
| [Sort a Vector of Floats][ex-sort-floats] | [![std-badge]][std] | [![cat-science-badge]][cat-science] |
13+
| [Sort a Vector of Structs by natural ordering][ex-sort-structs-natural] | [![std-badge]][std] | [![cat-science-badge]][cat-science] |
14+
| [Sort a Vector of Structs by custom criteria][ex-sort-structs-custom] | [![std-badge]][std] | [![cat-science-badge]][cat-science] |
1115

1216
[ex-rand]: algorithms/randomness.html#generate-random-numbers
1317
[ex-rand-range]: algorithms/randomness.html#generate-random-numbers-within-a-range
1418
[ex-rand-dist]: algorithms/randomness.html#generate-random-numbers-with-given-distribution
1519
[ex-rand-custom]: algorithms/randomness.html#generate-random-values-of-a-custom-type
1620
[ex-rand-passwd]: algorithms/randomness.html#create-random-passwords-from-a-set-of-alphanumeric-characters
1721
[ex-rand-choose]: algorithms/randomness.html#create-random-passwords-from-a-set-of-user-defined-characters
22+
[ex-sort-integers]: algorithms/sorting.html#sort-a-vector-of-integers
23+
[ex-sort-floats]: algorithms/sorting.html#sort-a-vector-of-floats
24+
[ex-sort-structs-natural]: algorithms/sorting.html#sort-a-vector-of-structs-by-natural-ordering
25+
[ex-sort-structs-custom]: algorithms/sorting.html#sort-a-vector-of-structs-by-custom-criteria
1826

1927
{{#include links.md}}

src/algorithms/sorting.md

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,8 @@
1+
# Sorting Vectors
2+
3+
{{#include sorting/sort.md}}
4+
{{#include sorting/sort_float.md}}
5+
{{#include sorting/sort_struct_natural.md}}
6+
{{#include sorting/sort_struct_custom.md}}
7+
8+
{{#include ../links.md}}

src/algorithms/sorting/sort.md

Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,20 @@
1+
## Sort a Vector of Integers
2+
3+
[![std-badge]][std] [![cat-science-badge]][cat-science]
4+
5+
This example sorts a Vector of integers via [`vec::sort`]. Alternative would
6+
be to use [`vec::sort_unstable`] which can be faster, but does not preserve
7+
the order of equal elements.
8+
9+
```rust
10+
fn main() {
11+
let mut vec = vec![1, 5, 10, 2, 15];
12+
13+
vec.sort();
14+
15+
assert_eq!(vec, vec![1, 2, 5, 10, 15]);
16+
}
17+
```
18+
19+
[`vec::sort`]: https://doc.rust-lang.org/std/vec/struct.Vec.html#method.sort
20+
[`vec::sort_unstable`]: https://doc.rust-lang.org/std/vec/struct.Vec.html#method.sort_unstable

src/algorithms/sorting/sort_float.md

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,18 @@
1+
## Sort a Vector of Floats
2+
3+
[![std-badge]][std] [![cat-science-badge]][cat-science]
4+
5+
A Vector of f32 or f64 can be sorted with [`vec::sort_by`] and [`PartialOrd::partial_cmp`].
6+
7+
```rust
8+
fn main() {
9+
let mut vec = vec![1.1, 1.15, 5.5, 1.123, 2.0];
10+
11+
vec.sort_by(|a, b| a.partial_cmp(b).unwrap());
12+
13+
assert_eq!(vec, vec![1.1, 1.123, 1.15, 2.0, 5.5]);
14+
}
15+
```
16+
17+
[`vec::sort_by`]: https://doc.rust-lang.org/std/primitive.slice.html#method.sort_by
18+
[`PartialOrd::partial_cmp`]: https://doc.rust-lang.org/std/cmp/trait.PartialOrd.html#tymethod.partial_cmp
Lines changed: 55 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,55 @@
1+
## Sort a Vector of Structs by custom criteria
2+
3+
[![std-badge]][std] [![cat-science-badge]][cat-science]
4+
5+
This example sorts a Vector of Person structs by age. This is achieved
6+
with [`vec:sort_by`] and providing it with custom comparator function.
7+
8+
```rust
9+
use std::fmt;
10+
11+
struct Person {
12+
name: String,
13+
age: u32
14+
}
15+
16+
impl Person {
17+
pub fn new(name: String, age: u32) -> Self {
18+
Person {
19+
name,
20+
age
21+
}
22+
}
23+
}
24+
25+
impl PartialEq for Person {
26+
fn eq(&self, other: &Person) -> bool {
27+
self.name == other.name
28+
}
29+
}
30+
31+
impl fmt::Debug for Person {
32+
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
33+
write!(f, "{}", self.name)
34+
}
35+
}
36+
37+
fn main() {
38+
let expected = vec![
39+
Person::new("Al".to_string(), 60),
40+
Person::new("Zoe".to_string(), 25),
41+
Person::new("John".to_string(), 1),
42+
];
43+
44+
let mut people = vec![
45+
Person::new("Zoe".to_string(), 25),
46+
Person::new("Al".to_string(), 60),
47+
Person::new("John".to_string(), 1)];
48+
49+
people.sort_by(|a, b| b.age.cmp(&a.age));
50+
51+
assert_eq!(people, expected);
52+
}
53+
```
54+
55+
[`vec:sort_by`]: https://doc.rust-lang.org/std/vec/struct.Vec.html#method.sort_by
Lines changed: 70 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,70 @@
1+
## Sort a Vector of Structs by natural ordering
2+
3+
[![std-badge]][std] [![cat-science-badge]][cat-science]
4+
5+
Sorts a Vector of Person structs with a single property `name` by its natural
6+
order (By name). In order to make Person sortable you need four traits [`Eq`],
7+
[`PartialEq`], [`Ord`] and [`PartialOrd`]. Eq can be simply derived.
8+
9+
```rust
10+
use std::{cmp, fmt};
11+
12+
#[derive(Eq)]
13+
struct Person {
14+
name: String
15+
}
16+
17+
impl Person {
18+
pub fn new(name: String) -> Self {
19+
Person {
20+
name,
21+
}
22+
}
23+
}
24+
25+
impl PartialOrd for Person {
26+
fn partial_cmp(&self, other: &Person) -> Option<cmp::Ordering> {
27+
Some(other.cmp(self))
28+
}
29+
}
30+
31+
impl Ord for Person {
32+
fn cmp(&self, other: &Person) -> cmp::Ordering {
33+
self.name.cmp(&other.name)
34+
}
35+
}
36+
37+
impl PartialEq for Person {
38+
fn eq(&self, other: &Person) -> bool {
39+
self.name == other.name
40+
}
41+
}
42+
43+
impl fmt::Debug for Person {
44+
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
45+
write!(f, "{}", self.name)
46+
}
47+
}
48+
49+
fn main() {
50+
let expected = vec![
51+
Person::new("Zoe".to_string()),
52+
Person::new("John".to_string()),
53+
Person::new("Al".to_string())
54+
];
55+
56+
let mut people = vec![
57+
Person::new("Zoe".to_string()),
58+
Person::new("Al".to_string()),
59+
Person::new("John".to_string())];
60+
61+
people.sort();
62+
63+
assert_eq!(people, expected);
64+
}
65+
```
66+
67+
[`Eq`]: https://doc.rust-lang.org/std/cmp/trait.Eq.html
68+
[`PartialEq`]: https://doc.rust-lang.org/std/cmp/trait.PartialEq.html
69+
[`Ord`]: https://doc.rust-lang.org/std/cmp/trait.Ord.html
70+
[`PartialOrd`]: https://doc.rust-lang.org/std/cmp/trait.PartialOrd.html

0 commit comments

Comments
 (0)