Sort an array in wave form

 

Given an sorted array arr[] of integers, rearrange the elements into a wave-like array. An array arr[0..n-1] is said to be in wave form if it follows the pattern: arr[0]arr[1]arr[2]arr[3]arr[4] and so on and find the lexicographically smallest one.

Note: The given array is sorted in ascending order, and modify the given array in-place without returning a new array.

Input: arr[] = [1, 2, 3, 4, 5]
Output: [2, 1, 4, 3, 5]
Explanation: Array elements after sorting it in the waveform are 2, 1, 4, 3, 5.

Input: arr[] = [2, 4, 7, 8, 9, 10]
Output: [4, 2, 8, 7, 10, 9]
Explanation: Array elements after sorting it in the waveform are 4, 2, 8, 7, 10, 9.

 

class solution{

    public int[] arrWave(int[] arr){

        int n = arr.length;

        for(int i = 0 ; i < n-1  ; i = i +1){

            int temp = arr[i];

            arr[i] = arr[i+1];

            arr[i+1] = temp;

        }

    }

Comments

Popular Posts