Skip to content

Commit a9d98d8

Browse files
authored
add rust quicksort (#292)
* add rust quicksort * remove binary search from quicksort
1 parent 1de675e commit a9d98d8

File tree

3 files changed

+111
-0
lines changed

3 files changed

+111
-0
lines changed

04_quicksort/rust/Cargo.lock

Lines changed: 7 additions & 0 deletions
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

04_quicksort/rust/Cargo.toml

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,6 @@
1+
[package]
2+
name = "quicksort"
3+
version = "0.1.0"
4+
edition = "2021"
5+
6+
[dependencies]

04_quicksort/rust/src/main.rs

Lines changed: 98 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,98 @@
1+
fn rec_sum(list: &[usize]) -> usize {
2+
match list.get(0) {
3+
Some(x) => x + rec_sum(&list[1..]),
4+
None => 0,
5+
}
6+
}
7+
8+
fn rec_count<T>(list: &[T]) -> usize {
9+
match list.get(0) {
10+
Some(_) => 1 + rec_count(&list[1..]),
11+
None => 0,
12+
}
13+
}
14+
15+
fn maximum<T: Ord>(list: &[T]) -> Option<&T> {
16+
match list.get(0) {
17+
Some(x) => match maximum(&list[1..]) {
18+
Some(max) => {
19+
if x > max {
20+
Some(x)
21+
} else {
22+
Some(max)
23+
}
24+
}
25+
None => Some(x),
26+
},
27+
None => None,
28+
}
29+
}
30+
31+
fn quicksort<T: Ord + Clone>(list: &Vec<T>) -> Vec<T> {
32+
if list.len() < 2 {
33+
list.to_vec()
34+
} else {
35+
let pivot = &list[0];
36+
37+
let mut less = vec![];
38+
let mut greater = vec![];
39+
40+
for x in &list[1..] {
41+
if x <= pivot {
42+
less.push(x.clone());
43+
} else {
44+
greater.push(x.clone());
45+
}
46+
}
47+
48+
let mut new = Vec::with_capacity(list.len());
49+
new.append(&mut quicksort(&less));
50+
new.push(pivot.clone());
51+
new.append(&mut quicksort(&greater));
52+
new
53+
}
54+
}
55+
56+
fn main() {
57+
let list = vec![10, 5, 2, 12, 3];
58+
59+
println!("quicksort: {:?}", quicksort(&list));
60+
println!("sum: {}", rec_sum(&list));
61+
println!("count: {}", rec_count(&list));
62+
println!("maximum: {:?}", maximum(&list));
63+
}
64+
65+
#[cfg(test)]
66+
mod test {
67+
use super::*;
68+
69+
#[test]
70+
fn simple_rec_sum() {
71+
let list = [2, 4, 6];
72+
let expected = 12;
73+
74+
let result = rec_sum(&list);
75+
76+
assert_eq!(result, expected);
77+
}
78+
79+
#[test]
80+
fn simple_rec_count() {
81+
let list = [2, 4, 6];
82+
let expected = 3;
83+
84+
let result = rec_count(&list);
85+
86+
assert_eq!(result, expected);
87+
}
88+
89+
#[test]
90+
fn simple_maximum() {
91+
let list = [2, 4, 6, 3];
92+
let expected = 6;
93+
94+
let result = maximum(&list);
95+
96+
assert_eq!(result, Some(&expected));
97+
}
98+
}

0 commit comments

Comments
 (0)