Google Interview - Wiggle Sort

The wiggle problem, given an array of integers arrange them such that alternate elements are large and small.(2,5,3,6,...)

void sort_array(int[] s){
    int n = s.length;
    if(n == 0) return;
    
    boolean flag = true;
    int current = s[0];
    for (int i = 0; i < n-1; i++) {
        if ((flag && current > s[i+1]) || (!flag && current < s[i+1])) {
            s[i] = s[i+1];
        } else {
            s[i] = current;
            current = s[i+1];
        }
        flag = !flag;
    }
    s[n-1] = current;
}

Reference:

http://www.mitbbs.com/article_t1/JobHunting/32575573_0_1.html 

http://www.fgdsb.com/2015/01/20/special-sorting/

你可能感兴趣的:(Google Interview - Wiggle Sort)