Wave Array in Java: Explanation & Practice

Convert array to wave form

Problem summary

Arrange array in wave form: arr[0] >= arr[1] <= arr[2] >= arr[3]...

Starter code

public class Main {
    public static void main(String[] args) {
        int[] arr = {1, 2, 3, 4, 5}; // Test case 1
        
        // Convert to wave form
        // Print elements space-separated
    }
}

Expected output and test cases

  • Wave of [1,2,3,4,5]
    2 1 4 3 5
  • Wave of 6 elements
    2 1 4 3 6 5
  • Wave of 3 elements
    2 1 3

Hints

  1. Swap adjacent pairs at even indices
  2. Swap arr[i] and arr[i+1] for i=0,2,4...
  3. Works on sorted or unsorted arrays

Related Arrays exercises

Practice all Arrays exercises · Run this idea in the Java compiler