Sort an array in wave form

Sort Array in Waveform in Java

Sort Array in Waveform in Java

We are given an unsorted array of integers our motive is to sort the array into a wave-like array. 

It is a simple java program with a trick in it one solution is to use sorting. First sort the input array, then swap all adjacent elements. let us discuss how to do this problem.

For Example:

Input: arr[ ] = {20, 10, 8, 6, 4, 2}

Output: arr[ ] = {20, 8, 10, 4, 6, 2}

OR 

{10, 8, 20, 2, 6, 4} 

ALGORITHM TO PROBLEM STATEMENT:

  • START
  • INITIALIZE ARRAY WITH INPUTS
  • SORT THE ARRAY IN ASCENDING ORDER.
  • SWAP ADJACENT VALUE IN SWAPPED ARRAY.
  • PRINT NEW ARRAY 
  • END 

Java Code :

// Java implementation of problem statement
import java.util.*; 
class prepinsta 
    // A  method to swap two numbers. 
    void swap(int arr[], int aint b
    { 
        int temp = arr[a]; 
        arr[a] = arr[b]; 
        arr[b] = temp; 
    } 

    
    
    void sortwave(int arr[], int n
    { 
        // Sort the input array 
        Arrays.sort(arr); 

        // Swap adjacent elements 
        for (int i=0; i<n-1; i += 2
            swap(arr, i, i+1); 
    } 

    // Driver method 
    public static void main(String args[]) 
    { 
        prepinsta p = new prepinsta(); 
        int arr[] = {10904921523}; 
        int n = arr.length
        p.sortwave(arr, n); 
        for (int i : arr) 
            System.out.print(i + ” “); 
    } 


Output:

2 1 10 5 49 23 90