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 second element should be maximum of all elements present in the list. Similarly, third element will be next minimum element and fourth element is next maximum element and so on. Use of extra space is not permitted.
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 –
1 8 2 7 3 6 4 5
This article is contributed by Aditya Goel. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to firstname.lastname@example.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.
- Modify array by merging elements with addition such that it consists of only Primes.
- Rearrange array in alternating positive & negative items with O(1) extra space | Set 1
- Rearrange array in alternating positive & negative items with O(1) extra space | Set 2
- Count of subsequences which consists exactly K prime numbers
- Count pairs whose sum consists of set bits only
- Maximum length Subsequence with alternating sign and maximum Sum
- Rearrange array such that even index elements are smaller and odd index elements are greater
- Longest alternating subsequence which has maximum sum of elements
- Alternating split of a given Singly Linked List | Set 1
- Rearrange a linked list such that all even and odd positioned nodes are together
- Rearrange array such that difference of adjacent elements is in descending order
- Rearrange array such that all even-indexed elements in the Array is even
- Rearrange an array such that product of every two consecutive elements is a multiple of 4
- Sort a linked list that is sorted alternating ascending and descending orders?
- Recursive approach for alternating split of Linked List
- Longest alternating subsequence with maximum sum | Set 2
- Minimum cost required to rearrange a given array to make it equal to another given array
- Rearrange an array in maximum minimum form | Set 1
- Rearrange an array in maximum minimum form | Set 2 (O(1) extra space)
- Rearrange a given linked list in-place.