algorithmz/sorting/wiggle_sort.rs
1/// Returns the wiggle sorted version of the input.
2///
3/// Takes a list reference and returns a `Vec<i32>` or an error explaining the situation.
4///
5/// # Examples
6///
7/// Basic usage:
8/// ```
9/// let result = algorithmz::sorting::wiggle_sort(&[3, 5, 2, 1, 6, 4]).unwrap();
10/// assert_eq!(result,[3, 5, 1, 6, 2, 4]);
11/// ```
12///
13/// Match example:
14/// ```
15/// use algorithmz::sorting::wiggle_sort;
16/// match wiggle_sort(&[3, 5, 2, 1, 6, 4]) {
17/// Ok(n) => println!("The result was: {:?}",n),
18/// Err(e) => eprintln!("The error was: {}",e),
19/// }
20/// ```
21pub fn wiggle_sort(list: &[i32]) -> Result<Vec<i32>,String> {
22 if list.is_empty() {
23 return Err("Cannot use wiggle sort on an empty input!".to_string());
24 }
25 let mut result = list.to_vec();
26 for i in 1..result.len() {
27 if (i % 2 == 1) == (result[i-1] > result[i]) {
28 result.swap(i-1,i);
29 }
30 }
31 Ok(result)
32}
33