Given a list of integers, rearrange the list such that it consists of alternating minimum-maximum elements using only list operations. The first element of the list should be minimum and the second element should be the maximum of all elements present in the list. Similarly, the third element will be the next minimum element and the fourth element is the next maximum element, and so on. Use of extra space is not permitted. Examples:
Input: [1 3 8 2 7 5 6 4] Output: [1 8 2 7 3 6 4 5] Input: [1 2 3 4 5 6 7] Output: [1 7 2 6 3 5 4] Input: [1 6 2 5 3 4] Output: [1 6 2 5 3 4]
The idea is to sort the list in ascending order first. Then we start popping elements from the end of the list and insert them into their correct position in the list. Below is the implementation of above idea –
Java
// Java program to rearrange a given list // such that it consists of alternating // minimum maximum elements import java.util.*; class AlternateSort { // Function to rearrange a given list // such that it consists of alternating // minimum maximum elements using LinkedList public static void alternateSort(LinkedList<Integer> ll) { Collections.sort(ll); for ( int i = 1 ; i < (ll.size() + 1 )/ 2 ; i++) { Integer x = ll.getLast(); ll.removeLast(); ll.add( 2 *i - 1 , x); } System.out.println(ll); } public static void main (String[] args) throws java.lang.Exception { // Input list Integer arr[] = { 1 , 3 , 8 , 2 , 7 , 5 , 6 , 4 }; // Convert array to LinkedList LinkedList<Integer> ll = new LinkedList<Integer>(Arrays.asList(arr)); // Rearrange the given list alternateSort(ll); } } |
Output:
1 8 2 7 3 6 4 5
Time Complexity: O(N*logN), as we are using a sort function.
Auxiliary Space: O(N), as we are using extra space.
Please refer complete article on Rearrange a given list such that it consists of alternating minimum maximum elements for more details!