|  | 
|  | 1 | +package me.ramswaroop.arrays.sorting; | 
|  | 2 | + | 
|  | 3 | +import java.util.Arrays; | 
|  | 4 | + | 
|  | 5 | +/** | 
|  | 6 | + * Wiggle Sort: Arrange the elements in the array such that elements in | 
|  | 7 | + * even indices are greater than or equal to its neighbouring elements | 
|  | 8 | + * and elements in odd indices are less than or equal to its neighbouring | 
|  | 9 | + * elements. In other words, all elements in array {@code a} are arranged | 
|  | 10 | + * such that, a[i-1] <= a[i] => a[i+1] | 
|  | 11 | + * <p> | 
|  | 12 | + * Ex: {1, 3, 2, 5, 4, 6} | 
|  | 13 | + * | 
|  | 14 | + * @author ramswaroop | 
|  | 15 | + * @version 01/09/2016 | 
|  | 16 | + */ | 
|  | 17 | +public class WiggleSort { | 
|  | 18 | + | 
|  | 19 | +    public static int[] wiggleSortEasyWay(int[] a) { | 
|  | 20 | +        a = MergeSort.mergeSort(a); | 
|  | 21 | +        for (int i = 1; i < a.length; i += 2) { | 
|  | 22 | +            swap(a, i, i + 1); | 
|  | 23 | +        } | 
|  | 24 | +        return a; | 
|  | 25 | +    } | 
|  | 26 | + | 
|  | 27 | +    private static void swap(int[] a, int index1, int index2) { | 
|  | 28 | +        if (index2 >= a.length) return; | 
|  | 29 | + | 
|  | 30 | +        a[index1] = a[index1] + a[index2]; | 
|  | 31 | +        a[index2] = a[index1] - a[index2]; | 
|  | 32 | +        a[index1] = a[index1] - a[index2]; | 
|  | 33 | +    } | 
|  | 34 | + | 
|  | 35 | +    public static void main(String[] a) { | 
|  | 36 | +        int[] ar = {3, 5, 6, 7, 8, 1, 2}; | 
|  | 37 | +        System.out.println(Arrays.toString(wiggleSortEasyWay(ar))); | 
|  | 38 | +        int[] ar1 = {3, 5, 6, 7, 2, 1}; | 
|  | 39 | +        System.out.println(Arrays.toString(wiggleSortEasyWay(ar1))); | 
|  | 40 | +        int[] ar2 = {3, 5, 6, 7, 8, 1}; | 
|  | 41 | +        System.out.println(Arrays.toString(wiggleSortEasyWay(ar2))); | 
|  | 42 | +        int[] ar3 = {3, 5, 6, 5, 8, 1}; | 
|  | 43 | +        System.out.println(Arrays.toString(wiggleSortEasyWay(ar3))); | 
|  | 44 | +    } | 
|  | 45 | +} | 
0 commit comments