8000 Create quick-sort.rs · glitches-coder/Algorithms@179d3dc · GitHub
[go: up one dir, main page]

Skip to content

Commit 179d3dc

Browse files
authored
Create quick-sort.rs
1 parent aa459d8 commit 179d3dc

File tree

1 file changed

+43
-0
lines changed

1 file changed

+43
-0
lines changed

Sorting/quickSort/Rust/quick-sort.rs

Lines changed: 43 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,43 @@
1+
pub fn quick_sort<T: Ord>(arr: &mut [T]) {
2+
let len = arr.len();
3+
_quick_sort(arr, 0, (len - 1) as isize);
4+
}
5+
6+
fn _quick_sort<T: Ord>(arr: &mut [T], low: isize, high: isize) {
7+
if low < high {
8+
let p = partition(arr, low, high);
9+
_quick_sort(arr, low, p - 1);
10+
_quick_sort(arr, p + 1, high);
11+
}
12+
}
13+
14+
fn partition<T: Ord>(arr: &mut [T], low: isize, high: isize) -> isize {
15+
let pivot = high as usize;
16+
let mut store_index = low - 1;
17+
let mut last_index = high;
18+
19+
loop {
20+
store_index += 1;
21+
while arr[store_index as usize] < arr[pivot] {
22+
store_index += 1;
23+
}
24+
last_index -= 1;
25+
while last_index >= 0 && arr[last_index as usize] > arr[pivot] {
26+
last_index -= 1;
27+
}
28+
if store_index >= last_index {
29+
break;
30+
} else {
31+
arr.swap(store_index as usize, last_index as usize);
32+
}
33+
}
34+
arr.swap(store_index as usize, pivot as usize);
35+
store_index
36+
}
37+
fn main() {
38+
println!("Sort numbers ascending");
39+
let mut numbers = [4, 65, 2, -31, 0, 99, 2, 83, 782, 1];
40+
println!("Before: {:?}", numbers);
41+
quick_sort(&mut numbers);
42+
println!("After: {:?}\n", numbers);
43+
}

0 commit comments

Comments
 (0)
0