Algorithms-and-Data-Structures/Rust-Sort-Comparer/src/sorter.rs
2024-05-02 20:14:36 +01:00

150 lines
3.6 KiB
Rust

trait IsSorted<T> {
fn is_sorted(&self) -> bool;
}
impl<T: PartialOrd> IsSorted for Vec<T> {
fn is_sorted(&self) -> bool {
for i in 1..self.len() {
if self[i - 1] > self[i] {
return false
}
}
true
}
}
trait Quicksort<T> {
pub fn quicksort(&mut self, left: usize, right: usize);
fn partition(&mut self, mut left: usize, mut right: usize);
}
impl<T: PartialOrd> Quicksort<T> for Vec<T> {
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<usize>
}
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<usize>) -> Vec<usize> {
if array.len() < 2 {
return array
}
let mid = array.len() / 2;
let end = array.len();
let left: Vec<usize> = self.mergesort_private(array[0..mid].into());
let right: Vec<usize> = self.mergesort_private(array[mid..end].into());
let mut i = 0;
let mut j = 0;
let mut arr: Vec<usize> = 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);
}
}