Skip to content

Instantly share code, notes, and snippets.

@chuckremes
Last active August 29, 2015 13:56
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save chuckremes/9080237 to your computer and use it in GitHub Desktop.
Save chuckremes/9080237 to your computer and use it in GitHub Desktop.
/*
Lesson:
Wrapping it all up into a struct & impl.
*/
struct BubbleSort;
impl BubbleSort {
fn new () -> BubbleSort { BubbleSort }
fn sort_by<T: Ord> (&self, vec: &mut [T], compare: |&T,&T| -> Ordering) {
let mut right: uint = vec.len() - 1;
let mut swapped = true;
while swapped {
swapped = false;
for i in range(0, right) {
//if vec[i] > vec[i+1] {
if compare(&vec[i], &vec[i+1]) == Greater {
vec.swap(i, i+1);
swapped = true;
}
}
right -= 1;
}
}
fn sort<T: Ord>(&self, vec: &mut [T]) {
self.sort_by(vec, |a,b| {
if a > b { Greater }
else { Less }
});
}
}
fn main() {
let mut int_vector: ~[int] = ~[9,4,1,7,8,2,6,5,5,3];
let sorter: BubbleSort = BubbleSort.new();
sorter.sort(int_vector);
for i in int_vector.iter() {
println!("value {:?}", i.to_str());
}
let mut fp_vector: ~[f64] = ~[9.7, 4.3, 1.1, 7.3, 8.9, 2.4, 6.6, 5.2, 5.2, 3.04];
sorter.sort(fp_vector);
for i in fp_vector.iter() {
println!("value {:?}", i.to_str());
}
}
cremes$ rustc bubblesort7.rs
bubblesort7.rs:44:27: 44:44 error: type `BubbleSort` does not implement any method in scope named `new`
bubblesort7.rs:44 let sorter: BubbleSort = BubbleSort.new();
^~~~~~~~~~~~~~~~~
error: aborting due to previous error
task 'rustc' failed at 'explicit failure', /opt/local/var/macports/build/_opt_mports_dports_lang_rust/rust/work/rust-0.9/src/libsyntax/diagnostic.rs:75
task '<main>' failed at 'explicit failure', /opt/local/var/macports/build/_opt_mports_dports_lang_rust/rust/work/rust-0.9/src/librustc/lib.rs:453
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment