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]
import java.util.Arrays;
class App {
private static void swapNumbers(int[] nums, int i, int j) {
int temp = nums[i];
nums[i] = nums[j];
nums[j] = temp;
}
public static void rearrangeArrayNums(int[] numsbers) {
for (int i = 1; i < numsbers.length; i += 2) {
if (numsbers[i - 1] > numsbers[i]) {
swapNumbers(numsbers, i - 1, i);
}
if (i + 1 < numsbers.length && numsbers[i + 1] > numsbers[i]) {
swapNumbers(numsbers, i + 1, i);
}
}
}
public static void main(String[] args) {
int[] nums = { 1, 2, 4, 9, 5, 3, 8, 7, 10, 12, 14 };
System.out.println("Original array:\n" + Arrays.toString(nums));
rearrangeArrayNums(nums);
System.out.println("\nArray with every second element is greater than its left and right elements:\n"
+ Arrays.toString(nums));
}
}
Comments
Leave a comment