-
Notifications
You must be signed in to change notification settings - Fork 145
/
sort.rs
47 lines (38 loc) · 1.18 KB
/
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
// This is a buggy quick sort implementation, QuickCheck will find the bug for you
extern crate quickcheck;
use quickcheck::quickcheck;
fn smaller_than<T: Clone + Ord>(xs: &[T], pivot: &T) -> Vec<T> {
return xs.iter().filter(|&x| *x < *pivot).map(|x| x.clone()).collect();
}
fn larger_than<T: Clone + Ord>(xs: &[T], pivot: &T) -> Vec<T> {
return xs.iter().filter(|&x| *x > *pivot).map(|x| x.clone()).collect();
}
fn sortk<T: Clone + Ord>(x: &T, xs: &[T]) -> Vec<T> {
let mut result : Vec<T> = sort(smaller_than(xs, x).as_slice());
let last_part = sort(larger_than(xs, x).as_slice());
result.push(x.clone());
result.extend(last_part.iter().map(|x| x.clone()));
result
}
fn sort<T: Clone + Ord>(list: &[T]) -> Vec<T> {
if list.is_empty() {
vec![]
} else {
sortk(&list[0], list.tail())
}
}
fn main() {
fn is_sorted(xs: Vec<int>) -> bool {
for win in xs.as_slice().windows(2) {
if win[0] > win[1] {
return false
}
}
true
}
fn keeps_length(xs: Vec<int>) -> bool {
xs.len() == sort(xs.as_slice()).len()
}
quickcheck(keeps_length);
quickcheck(is_sorted)
}