Last active
April 7, 2016 03:49
-
-
Save fero23/78fc665af58607e5e604f6b5e9ce02f5 to your computer and use it in GitHub Desktop.
Quickstort implementation in Rust
This file contains hidden or 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 = [3,11,7,89,85,4,39,51,15,9,74,57,60,22,46,48,79,25,72,5,80,27]; | |
arr.quicksort(); | |
println!("{:?}", arr); | |
} | |
trait Sortable: PartialOrd { | |
fn quicksort(&mut self); | |
} | |
impl<T> Sortable for [T] where T: PartialOrd + Copy { | |
fn quicksort(&mut self) { | |
fn partition<T>(arr: &mut [T], start: usize, end: usize) | |
where T: PartialOrd + Copy { | |
if end - start < 2 { | |
return; | |
} | |
let pivot = arr[(start + end) / 2]; | |
let mut left = start; | |
let mut right = end - 1; | |
loop { | |
while left < end && arr[left] < pivot {left += 1;} | |
while right > start && arr[right] > pivot {right -= 1;} | |
if left >= right { | |
partition(arr, start, left); | |
partition(arr, right + 1, end); | |
break; | |
} | |
let temp = arr[left]; | |
arr[left] = arr[right]; | |
arr[right] = temp; | |
left += 1; | |
right -= 1; | |
} | |
} | |
let end = self.len(); | |
partition(self, 0, end); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment