use std::time::{ Instant, Duration };
use rand::prelude::*;
use super::IsSorted;
pub trait Bogosort<T: PartialEq + PartialOrd + Clone + Copy> {
fn bogosort(&mut self);
fn bogosort_timed(&mut self) -> Duration;
fn bogosort_stepped(&mut self) -> Vec<Vec<T>>;
fn bogosort_stepped_and_timed(&mut self) -> (Vec<Vec<T>>, Duration);
}
impl<T> Bogosort<T> for Vec<T>
where T: PartialEq + PartialOrd + Clone + Copy,
{
fn bogosort(&mut self) {
if self.len() <= 1 {
return;
}
let mut rng = rand::thread_rng();
while !self.is_sorted() {
self.shuffle(&mut rng);
}
}
fn bogosort_timed(&mut self) -> Duration {
let time = Instant::now();
if self.len() <= 1 {
return time.elapsed();
}
let mut rng = rand::thread_rng();
while !self.is_sorted() {
self.shuffle(&mut rng);
}
return time.elapsed();
}
fn bogosort_stepped(&mut self) -> Vec<Vec<T>> {
let mut steps = vec![self.clone()];
if self.len() <= 1 {
return steps;
}
let mut rng = rand::thread_rng();
while !self.is_sorted() {
self.shuffle(&mut rng);
steps.push(self.clone());
}
return steps;
}
fn bogosort_stepped_and_timed(&mut self) -> (Vec<Vec<T>>, Duration) {
let time = Instant::now();
let mut steps = vec![self.clone()];
if self.len() <= 1 {
return (steps, time.elapsed());
}
let mut rng = rand::thread_rng();
while !self.is_sorted() {
self.shuffle(&mut rng);
steps.push(self.clone());
}
(steps, time.elapsed())
}
}
pub fn bogosort<T>(mut arr: Vec<T>) -> Vec<T>
where T: PartialEq + PartialOrd + Clone + Copy,
{
if arr.len() <= 1 {
return arr;
}
let mut rng = rand::thread_rng();
while !arr.is_sorted() {
arr.shuffle(&mut rng);
}
return arr;
}
pub fn bogosort_timed<T>(mut arr: Vec<T>) -> (Vec<T>, Duration)
where T: PartialEq + PartialOrd + Clone + Copy,
{
let time = Instant::now();
if arr.len() <= 1 {
return (arr, time.elapsed());
}
let mut rng = rand::thread_rng();
while !arr.is_sorted() {
arr.shuffle(&mut rng);
}
(arr, time.elapsed())
}
pub fn bogosort_stepped<T>(mut arr: Vec<T>) -> (Vec<T>, Vec<Vec<T>>)
where T: PartialEq + PartialOrd + Clone + Copy,
{
let mut steps = vec![arr.clone()];
if arr.len() <= 1 {
return (arr, steps);
}
let mut rng = rand::thread_rng();
while !arr.is_sorted() {
arr.shuffle(&mut rng);
steps.push(arr.clone());
}
(arr, steps)
}
pub fn bogosort_stepped_and_timed<T>(mut arr: Vec<T>) -> (Vec<T>, Vec<Vec<T>>, Duration)
where T: PartialEq + PartialOrd + Clone + Copy,
{
let time = Instant::now();
let mut steps = vec![arr.clone()];
if arr.len() <= 1 {
return (arr, steps, time.elapsed());
}
let mut rng = rand::thread_rng();
while !arr.is_sorted() {
arr.shuffle(&mut rng);
steps.push(arr.clone());
}
(arr, steps, time.elapsed())
}