-
Notifications
You must be signed in to change notification settings - Fork 4
Expand file tree
/
Copy pathproblem_7_1_hoare_partition_correctness.rs
More file actions
62 lines (52 loc) · 1.21 KB
/
Copy pathproblem_7_1_hoare_partition_correctness.rs
File metadata and controls
62 lines (52 loc) · 1.21 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
// Hoare-Partition(A, p, r)
// 1 x = A[p]
// 2 i = p - 1
// 3 j = r + 1
// 4 while True
// 5 repeat
// 6 j = j - 1
// 7 until A[j] ≤ x
// 8 repeat
// 9 i = i + 1
// 10 until A[i] ≥ x
// 11 if i < j
// 12 exchange A[i] with A[j]
// 13 else return j
#[allow(clippy::many_single_char_names)] // Expected.
pub fn hoare_partition<T: Clone + Ord>(a: &mut [T], p: usize, r: usize) -> usize {
let x = a[p].clone();
let mut i = p;
let mut j = r;
loop {
loop {
j -= 1;
if a[j] <= x {
break;
}
}
while a[i] < x {
i += 1;
}
if i < j {
a.swap(i, j);
i += 1;
} else {
return j + 1;
}
}
}
pub fn hoare_quicksort<T: Clone + Ord>(a: &mut [T], p: usize, r: usize) {
if r - p > 1 {
let q = hoare_partition(a, p, r);
hoare_quicksort(a, p, q);
hoare_quicksort(a, q, r);
}
}
#[cfg(test)]
mod tests {
use crate::test_utilities;
#[test]
fn test_hoare_quicksort() {
test_utilities::run_all_sorting_tests(|a| super::hoare_quicksort(a, 0, a.len()));
}
}