Wednesday, June 10, 2026
HomeData Modelling & AIPython Program For Rearranging A Given List Such That It Consists Of...

Python Program For Rearranging A Given List Such That It Consists Of Alternating Minimum Maximum Elements

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 – 

Python




# Python program to rearrange a given
# list such that it consists of alternating
# minimum maximum elements
inp = []
 
# Function to rearrange a given list such
# that it consists of alternating minimum
# maximum elements
def alternateSort():
 
    global inp
     
    # Sort the list in ascending order
    inp.sort()
 
    # Get index to first element of
    # the list
    it = 0
    it = it + 1
     
    i = 1
     
    while ( i < (len(inp) + 1)/2 ):   
        i = i + 1
         
        # pop last element (next greatest)
        val = inp[-1]
        inp.pop()
 
        # Insert it after next minimum
        # element
        inp.insert(it, val)
 
        # Increment the pointer for next
        # pair
        it = it + 2
     
# Driver code
# Input list
inp=[ 1, 3, 8, 2, 7, 5, 6, 4 ]
 
# Rearrange the given list
alternateSort()
 
# Print the modified list
print (inp)
 
# This code is contributed by Arnab Kundu


Output:

1 8 2 7 3 6 4 5

Time Complexity: O(N*logN), as we are using a sort function.

Auxiliary Space: O(1), as we are not using extra space.

Please refer complete article on Rearrange a given list such that it consists of alternating minimum maximum elements for more details!

Last Updated :
31 May, 2022
Like Article
Save Article


Previous

<!–

8 Min Read | Java

–>


Next


<!–

8 Min Read | Java

–>

Share your thoughts in the comments

RELATED ARTICLES

1 COMMENT

Most Popular

Dominic
32515 POSTS0 COMMENTS
Milvus
131 POSTS0 COMMENTS
Nango Kala
6896 POSTS0 COMMENTS
Nicole Veronica
12012 POSTS0 COMMENTS
Nokonwaba Nkukhwana
12109 POSTS0 COMMENTS
Shaida Kate Naidoo
7018 POSTS0 COMMENTS
Ted Musemwa
7262 POSTS0 COMMENTS
Thapelo Manthata
6976 POSTS0 COMMENTS
Umr Jansen
6963 POSTS0 COMMENTS