Java: Rearrange a given array of unique elements such that every second element of the array is greater than its left and right elements
Write a Java program to rearrange a given array of unique elements such that every second element of the array is greater than its left and right elements.
Example:
Input :
nums= { 1, 2, 4, 9, 5, 3, 8, 7, 10, 12, 14 }
Output:
Array with every second element is greater than its left and right elements:
[1, 4, 2, 9, 3, 8, 5, 10, 7, 14, 12]
Sample Solution:
Java Code:
Sample Output:
Original array: [1, 2, 4, 9, 5, 3, 8, 7, 10, 12, 14] Array with every second element is greater than its left and right elements: [1, 4, 2, 9, 3, 8, 5, 10, 7, 14, 12]
Flowchart:
For more Practice: Solve these Related Problems:
- Write a Java program to rearrange an array such that even-indexed elements are greater than their adjacent odd-indexed elements.
- Write a Java program to rearrange an array so that all odd numbers appear before even numbers while maintaining relative order.
- Write a Java program to find the smallest element that is greater than both its neighbors in an unsorted array.
- Write a Java program to rearrange an array such that elements at prime indices are greater than elements at non-prime indices.
Java Code Editor:
Previous: Write a Java program to shuffle a given array of integers.
Next: Write a Java program to find the equilibrium indices from a given array of integers.
What is the difficulty level of this exercise?
Test your Programming skills with w3resource's quiz.