Java: Sort an array of positive integers of a given array in the specified pattern
50. Sort array with alternate max-min values
Write a Java program to sort an array of positive integers from an array. In the sorted array the value of the first element should be maximum, the second value should be a minimum, third should be the second maximum, the fourth should be the second minimum and so on.
Sample Pattern:
[100, 10, 90, 20, 80, 30, 70, 40, 60, 50]
Sample Solution:
Java Code:
// Import the necessary Java utility class for working with arrays.
import java.util.Arrays;
// Define the Main class.
public class Main
{
// A method to rearrange an array with alternating smaller and larger elements.
static int[] rearrange(int[] new_arra, int n)
{
// Create a temporary array for the rearranged elements.
int temp[] = new int[n];
// Initialize pointers for the smallest and largest elements.
int small_num = 0, large_num = n - 1;
// Initialize a flag for alternating between small and large elements.
boolean flag = true;
// Iterate through the array and rearrange elements.
for (int i = 0; i < n; i++)
{
if (flag)
temp[i] = new_arra[large_num--];
else
temp[i] = new_arra[small_num++];
// Toggle the flag to switch between small and large elements.
flag = !flag;
}
return temp;
}
// The main method for executing the program.
public static void main(String[] args)
{
// Create an array of integers.
int nums[] = new int[]{10, 20, 30, 40, 50, 60, 70, 80, 90, 100};
int result[];
// Print the original array.
System.out.println("Original Array ");
System.out.println(Arrays.toString(nums));
// Rearrange the array.
result = rearrange(nums, nums.length);
// Print the rearranged array.
System.out.println("New Array ");
System.out.println(Arrays.toString(result));
}
}
Sample Output:
Original Array [10, 20, 30, 40, 50, 60, 70, 80, 90, 100] New Array [100, 10, 90, 20, 80, 30, 70, 40, 60, 50]
Flowchart:
For more Practice: Solve these Related Problems:
- Write a Java program to sort an array so that the first half is sorted in ascending order and the second half in descending order.
- Write a Java program to rearrange an array in an alternating high-low pattern without using extra space.
- Write a Java program to find the Kth largest and Kth smallest elements in an array without sorting it.
- Write a Java program to sort an array of 0s, 1s, and 2s in O(n) time complexity.
Go to:
PREV : Arrange array with positive integers before negatives.
NEXT : Separate 0s on left and 1s on right in array.
Java Code Editor:
What is the difficulty level of this exercise?
Test your Programming skills with w3resource's quiz.