Created
July 8, 2017 14:23
-
-
Save eloytoro/c66c756e71f20edacf1984dc3734c815 to your computer and use it in GitHub Desktop.
most trivial implementation of quick_sort I could come up with
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
fn main() { | |
let mut arr = vec![ | |
8, | |
4, | |
1, | |
10, | |
0, | |
3, | |
4, | |
3, | |
9 | |
]; | |
quick_sort(&mut arr); | |
for x in arr { | |
println!("{}", x); | |
} | |
} | |
fn quick_sort_helper(input: &mut Vec<i64>, f_index: usize, l_index: usize) { | |
let mut i = f_index; | |
let mut j = l_index; | |
let mut l = 1; | |
let mut r = 0; | |
loop { | |
if input[i] > input[j] { | |
input.swap(i, j); | |
// this makes it so each swap will start moving the opposite caret | |
// until another swap occurs | |
l ^= 1; | |
r ^= 1; | |
} | |
// stop when `i` and `j` are next to each other | |
if j - i == 1 { | |
break; | |
} | |
i += l; | |
j -= r; | |
} | |
if f_index != i { | |
quick_sort_helper(input, f_index, i); | |
} | |
if l_index != j { | |
quick_sort_helper(input, j, l_index); | |
} | |
} | |
fn quick_sort(input: &mut Vec<i64>) { | |
let len = input.len(); | |
quick_sort_helper(input, 0, len - 1); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment