1
use std::cmp::Ordering::{Equal, Greater, Less};4
pub fn wiggle_sort(nums: &mut Vec<i32>) {5
if Self::wiggle_forward(&mut nums[..]) {8
if Self::wiggle_backward(&mut nums[..]) {12
if Self::wiggle_pivot(&mut nums[..], pivot) {15
panic!("not wiggle-sortable");17
fn wiggle_forward(nums: &mut [i32]) -> bool {20
while j < nums.len() {22
// (0) 0 <= i <= j <= nums.len, i < nums.len23
// (1) nums[..i+1] is wiggle-sorted24
// (2) nums[i..j] are all identical25
// (3) nums[j..] are unchanged since the start of the loop30
match (i % 2 == 0, i32::cmp(&nums[j], &nums[i])) {31
(true, Greater) | (false, Less) => {40
(true, Less) | (false, Greater) => {48
return i >= nums.len() - 1;50
fn wiggle_backward(nums: &mut [i32]) -> bool {51
let mut i = nums.len();52
let mut j = nums.len();55
// (0) 0 <= j <= i <= nums.len and 0 < i56
// (1) nums[i-1..] is wiggle-sorted57
// (2) nums[j..i] are all identical58
// (3) nums[..j] are unchanged since the start of the loop63
match (i % 2 == 0, i32::cmp(&nums[j - 1], &nums[i - 1])) {64
(true, Less) | (false, Greater) => {68
nums.swap(j - 1, i - 2);73
(true, Greater) | (false, Less) => {74
nums.swap(j - 1, i - 1);83
fn wiggle_pivot(nums: &mut [i32], pivot: i32) -> bool {86
let index = move |i: usize| {97
match nums[index(i)].cmp(&pivot) {99
nums.swap(index(i), index(min_i));107
nums.swap(index(i), index(max_i - 1));112
return min_i <= m && max_i >= m;