Answer to Question #309543 in Java | JSP | JSF for Kyle

Question #309543

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]


1
Expert's answer
2022-03-14T08:37:13-0400
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));
	}
}

Need a fast expert's response?

Submit order

and get a quick answer at the best price

for any assignment or question with DETAILED EXPLANATIONS!

Comments

No comments. Be the first!

Leave a comment

LATEST TUTORIALS
New on Blog
APPROVED BY CLIENTS