Java Zigzag Encode zigZagSort(int[] array)

Here you can find the source of zigZagSort(int[] array)

Description

Sort an array in zig-zag pattern i.e.

License

Open Source License

Parameter

Parameter Description
array input array

Return

zig-zag sorted array

Declaration

public static int[] zigZagSort(int[] array) 

Method Source Code

//package com.java2s;
//License from project: Open Source License 

public class Main {
    /**//  ww  w .  ja va 2 s  .  c om
     * Sort an array in zig-zag pattern 
     *    i.e. second element is larger than first,
     *       third is smaller than second,
     *       fourth is larger than third,
     *       and so on ...
     * @param array
     *       input array
     * @return   zig-zag sorted array
     */
    public static int[] zigZagSort(int[] array) {

        for (int i = 1; i < array.length; i++) {
            if ((i % 2 == 1 && array[i] < array[i - 1]) || (i % 2 == 0 && array[i] > array[i - 1])) {
                int temp = array[i];
                array[i] = array[i - 1];
                array[i - 1] = temp;
            }
        }

        return array;
    }
}

Related

  1. zigzagEncode(int input)
  2. zigzagEncode(int input)
  3. zigZagEncode(long l)
  4. zigZagEncode(long n)
  5. zigzagEncode(long val)
  6. zigzagToInt(final int n)