Created
December 6, 2015 10:33
-
-
Save zummenix/541cc21c35e6780d1b74 to your computer and use it in GitHub Desktop.
quicksort implementation using rust
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 v = vec![4, 6, 7, 8, 5, 1, 2, 3, 15, 10, 35, 8, 2, 1, 201, 100]; | |
println!("before: {:?}", v); | |
sort_in_place(&mut v); | |
println!("after: {:?}", v); | |
} | |
fn sort_in_place(a: &mut [u32]) { | |
match a.len() { | |
0 | 1 => (), | |
2 => if a[1] < a[0] { a.swap(0, 1) }, | |
_ => { | |
let pi = partition(a); | |
println!("a {:?}", a); | |
sort_in_place(&mut a[..pi]); | |
sort_in_place(&mut a[pi + 1..]); | |
} | |
} | |
} | |
fn partition(a: &mut [u32]) -> usize { | |
let len = a.len(); | |
let pi = a.len() - 1; | |
a.swap(len / 2, pi); // Take pivot element from the middle and move to the end. | |
let mut i = 0; | |
let mut j = 0; | |
while j < pi { | |
if a[j] < a[pi] { | |
a.swap(i, j); | |
i += 1; | |
} | |
j += 1; | |
} | |
a.swap(i, pi); | |
i | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment