trait IsSorted { fn is_sorted(&self) -> bool; } impl IsSorted for Vec { fn is_sorted(&self) -> bool { for i in 1..self.len() { if self[i - 1] > self[i] { return false } } true } } trait Quicksort { pub fn quicksort(&mut self, left: usize, right: usize); fn partition(&mut self, mut left: usize, mut right: usize); } impl Quicksort for Vec { fn quicksort(&mut self, left: usize, right: usize) { if left < right { let pivot = self.partition(left, right); self.quicksort(left, pivot); self.quicksort(pivot + 1, right); } } fn partition(&mut self, mut left: usize, mut right: usize) -> usize { let pivot = &self[left]; while left < right { while self[left] < pivot { left += 1; } while self[right] > pivot { right -= 1; } self.swap(left, right); } left } } pub struct Sorter { pub array: Vec } impl Sorter { pub fn bubblesort(&mut self) { for i in 0..self.array.len()-1 { let mut swaps = false; for j in 1..self.array.len()-i { if self.array[j] < self.array[j-1] { let temp = self.array[j]; self.array[j] = self.array[j-1]; self.array[j-1] = temp; swaps = true; } } if !swaps {break}; } } pub fn insertsort(&mut self) { for i in 1..self.array.len() { let key = self.array[i]; let mut j = (i - 1) as isize; while j >= 0 && self.array[j as usize] > key { self.array[(j + 1) as usize] = self.array[j as usize]; j -= 1; } self.array[(j + 1) as usize] = key; } } pub fn mergesort(&mut self) { self.array = self.mergesort_private(self.array.clone()); } fn mergesort_private(&self, array: Vec) -> Vec { if array.len() < 2 { return array } let mid = array.len() / 2; let end = array.len(); let left: Vec = self.mergesort_private(array[0..mid].into()); let right: Vec = self.mergesort_private(array[mid..end].into()); let mut i = 0; let mut j = 0; let mut arr: Vec = vec![]; while i < left.len() && j < right.len() { if left[i] <= right[j] { arr.push(left[i]); i += 1; } else { arr.push(right[j]); j += 1; } } while i < left.len() { arr.push(left[i]); i += 1; } while j < right.len() { arr.push(right[j]); j += 1; } arr } pub fn binary_search(&self, search_item: usize) { let mut end: usize = self.array.len(); let mut start: usize = 0; while start <= end { let mid = (start + end) / 2; if self.array[mid] == search_item { println!("{} was found at index {}", search_item, mid); return; } else if self.array[mid] > search_item { end = mid - 1; } else { start = mid + 1; } } println!("{} was not found in list", search_item); } }