Skip to content

Instantly share code, notes, and snippets.

@balajahe
Last active December 31, 2019 20:05
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 balajahe/fb72018b70f31aceaae0ad0461c7c9ad to your computer and use it in GitHub Desktop.
Save balajahe/fb72018b70f31aceaae0ad0461c7c9ad to your computer and use it in GitHub Desktop.
Императивная и функциональная реализация быстрой сортировки на Rust
/*
[dependencies]
rand = "0.7"
*/
fn main() {
use rand::Rng;
let mut rng = rand::thread_rng();
let mut arr = (1..10_000_000).map(|_| rng.gen::<f64>()).collect();
let tbegin = std::time::SystemTime::now();
//sort_imp(&mut arr);
arr = sort_fun1(arr);
println!("{:?}", tbegin.elapsed().unwrap());
//println!("{:?}", arr);
}
fn sort_imp(arr: &mut Vec<f64>) {
fn swap(arr: &mut Vec<f64>, i: usize, j: usize) {
let t = arr[i];
arr[i] = arr[j];
arr[j] = t;
};
fn sort1(arr: &mut Vec<f64>, l: usize, r: usize) {
let pivot = arr[(l + r) / 2];
let mut i = l;
let mut j = r;
while i <= j {
while arr[i] < pivot { i += 1; }
while arr[j] > pivot { j -= 1; }
if i <= j {
swap(arr, i, j);
i += 1;
j -= 1;
}
}
if l < j { sort1(arr, l, j); }
if i < r { sort1(arr, i, r); }
};
if arr.len() > 1 {
sort1(arr, 0, arr.len() - 1);
}
}
fn sort_fun(arr: Vec<f64>) -> Vec<f64> {
if arr.len() <= 1 {
arr
} else {
let pivot = arr[arr.len() / 2];
let mut a = Vec::<f64>::with_capacity(arr.len());
a.append(&mut sort_fun(arr.iter().filter(|x| pivot > **x).cloned().collect()));
a.append(&mut arr.iter().filter(|x| pivot == **x).cloned().collect());
a.append(&mut sort_fun(arr.iter().filter(|x| pivot < **x).cloned().collect()));
a
}
}
fn sort_fun1(arr: Vec<f64>) -> Vec<f64> {
if arr.len() <= 1 {
arr
} else {
let pivot = arr[arr.len() / 2];
[
sort_fun(arr.iter().filter(|&&x| pivot > x).cloned().collect()),
arr.iter().filter(|&&x| pivot == x).cloned().collect(),
sort_fun(arr.iter().filter(|&&x| pivot < x).cloned().collect()),
]
.concat()
}
}
fn sort_fun2(arr: Vec<f64>) -> Vec<f64> {
if arr.len() <= 1 {
arr
} else {
let pivot = arr[arr.len() / 2];
let (a, b): (_, Vec<_>) = arr.into_iter().partition(|&x| pivot > x);
let (b, c) = b.into_iter().partition(|&x| pivot == x);
[sort_fun2(a), b, sort_fun2(c)].concat()
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment