forked from TheAlgorithms/Rust
-
Notifications
You must be signed in to change notification settings - Fork 1
/
sleep_sort.rs
77 lines (65 loc) · 1.71 KB
/
sleep_sort.rs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
use std::sync::mpsc;
use std::thread;
use std::time::Duration;
pub fn sleep_sort(vec: &[usize]) -> Vec<usize> {
let len = vec.len();
let (tx, rx) = mpsc::channel();
for &x in vec.iter() {
let tx: mpsc::Sender<usize> = tx.clone();
thread::spawn(move || {
thread::sleep(Duration::from_millis((20 * x) as u64));
tx.send(x).expect("panic");
});
}
let mut sorted_list: Vec<usize> = Vec::new();
for _ in 0..len {
sorted_list.push(rx.recv().unwrap())
}
sorted_list
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn empty() {
let mut arr: Vec<usize> = Vec::new();
let res = sleep_sort(&mut arr);
assert_eq!(res, &[]);
}
#[test]
fn single_element() {
let mut arr = vec![1];
let res = sleep_sort(&mut arr);
assert_eq!(res, &[1]);
}
#[test]
fn sorted_array() {
let mut arr = vec![1, 2, 3, 4];
let res = sleep_sort(&mut arr);
assert_eq!(res, &[1, 2, 3, 4]);
}
#[test]
fn unsorted_array() {
let mut arr = vec![3, 4, 2, 1];
let res = sleep_sort(&mut arr);
assert_eq!(res, &[1, 2, 3, 4]);
}
#[test]
fn odd_number_of_elements() {
let mut arr = vec![3, 1, 7];
let res = sleep_sort(&mut arr);
assert_eq!(res, &[1, 3, 7]);
}
#[test]
fn repeated_elements() {
let mut arr = vec![1, 1, 1, 1];
let res = sleep_sort(&mut arr);
assert_eq!(res, &[1, 1, 1, 1]);
}
#[test]
fn random_elements() {
let mut arr = vec![5, 3, 7, 10, 1, 0, 8];
let res = sleep_sort(&mut arr);
assert_eq!(res, &[0, 1, 3, 5, 7, 8, 10]);
}
}