85 lines
1.8 KiB
Rust
85 lines
1.8 KiB
Rust
use crate::{CompareResult, Sort};
|
|
|
|
pub struct QuickSort {
|
|
comparisons: u64,
|
|
swaps: u64,
|
|
should_print: bool,
|
|
}
|
|
|
|
impl QuickSort {
|
|
fn swap(&mut self, list: &mut Vec<u64>, i: usize, j: usize) {
|
|
self.swaps += 1;
|
|
list.swap(i, j);
|
|
}
|
|
fn compare(&mut self, a: u64, b: u64) -> CompareResult {
|
|
self.comparisons += 1;
|
|
if a < b {
|
|
CompareResult::LESS
|
|
} else if a > b {
|
|
CompareResult::GREATER
|
|
} else {
|
|
CompareResult::EQUAL
|
|
}
|
|
}
|
|
|
|
pub fn lomuto_partition(&mut self, list: &mut Vec<u64>) -> u64 {
|
|
let pivot = list.len() - 1;
|
|
let mut swap = 0;
|
|
|
|
for i in 0..pivot {
|
|
use CompareResult::*;
|
|
if self.compare(list[i as usize], list[pivot as usize]) == LESS {
|
|
if swap != i {
|
|
self.swap(list, swap, i);
|
|
}
|
|
swap += 1;
|
|
}
|
|
}
|
|
|
|
if swap != pivot {
|
|
self.swap(list, swap, pivot);
|
|
}
|
|
|
|
swap as u64
|
|
}
|
|
|
|
}
|
|
|
|
impl Sort for QuickSort {
|
|
fn new(should_print: bool) -> Self {
|
|
Self {
|
|
comparisons: 0,
|
|
swaps: 0,
|
|
should_print,
|
|
}
|
|
}
|
|
|
|
fn sort_mut(&mut self, list: &mut Vec<u64>) {
|
|
if list.len() > 1 {
|
|
let pivot = self.lomuto_partition(list);
|
|
|
|
if self.should_print {
|
|
println!("pivot = {pivot}:");
|
|
println!("{:?}", list);
|
|
}
|
|
|
|
self.sort_mut(&mut list[..pivot as usize].to_vec());
|
|
|
|
self.sort_mut(&mut list[pivot as usize + 1..].to_vec());
|
|
}
|
|
}
|
|
|
|
fn num_comp(&self) -> u64 {
|
|
self.comparisons
|
|
}
|
|
|
|
fn num_swap(&self) -> u64 {
|
|
self.swaps
|
|
}
|
|
|
|
fn reset_state(&mut self) {
|
|
self.comparisons = 0;
|
|
self.swaps = 0;
|
|
}
|
|
}
|
|
|