Last active
May 15, 2016 01:55
-
-
Save fero23/6b7c7e8c654cfb73dd7f99f58b26b7f1 to your computer and use it in GitHub Desktop.
Multiple sorting algorithms implemented using 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 vec = vec![23,6,2,7,8,43,3,7,9,2]; | |
println!("Shellsort: {:?}", vec.clone().shellsort()); | |
println!("Quicksort: {:?}", vec.clone().quicksort()); | |
println!("Heapsort : {:?}", vec.clone().heapsort()); | |
} | |
trait MultiSort { | |
fn shellsort(&mut self) -> &mut Self; | |
fn quicksort(&mut self) -> &mut Self; | |
fn heapsort(&mut self) -> &mut Self; | |
} | |
impl<T> MultiSort for [T] | |
where T: PartialOrd + PartialEq + Clone + Copy { | |
fn shellsort(&mut self) -> &mut Self { | |
let mut gap = self.len() / 2; | |
while gap != 0 { | |
for i in gap..self.len() { | |
let mut j = i - gap; | |
while self[j] > self[j + gap] { | |
self.swap(j, j + gap); | |
if j >= gap { | |
j -= gap; | |
} else { | |
break; | |
} | |
} | |
} | |
gap /= 2; | |
} | |
self | |
} | |
fn quicksort(&mut self) -> &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; | |
} | |
arr.swap(left, right); | |
left += 1; | |
right -= 1; | |
} | |
} | |
let end = self.len(); | |
partition(self, 0, end); | |
self | |
} | |
fn heapsort(&mut self) -> &mut Self { | |
fn sift_down<T>(arr: &mut [T], mut start: usize, end: usize) | |
where T: PartialOrd { | |
while start * 2 + 1 <= end { | |
let mut child = start * 2 + 1; | |
if child + 1 <= end && arr[child] < arr[child + 1] { | |
child = child + 1; | |
} | |
if arr[start] < arr[child] { | |
arr.swap(start, child); | |
start = child; | |
} else { | |
break; | |
} | |
} | |
} | |
fn heapify<T>(arr: &mut [T]) where T: PartialOrd { | |
let start = (arr.len() as i32 - 2) / 2; | |
if start > 0 { | |
for node in (0..start as usize - 1).rev() { | |
let len = arr.len(); | |
sift_down(arr, node, len - 1); | |
} | |
} | |
} | |
heapify(self); | |
let mut end = self.len() as i32 - 1; | |
while end > 0 { | |
self.swap(0, end as usize); | |
end -= 1; | |
sift_down(self, 0, end as usize); | |
} | |
self | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment