Menu Close

Re-order array, such that nums[0] < nums[1] > nums[2] < nums[3]….

Given an integer array nums, re-order it such that nums[0] < nums[1] > nums[2] < nums[3]....
You may assume the input array always has a valid answer.

Input: array_nums = [1,5,1,1,6,4]
Output: [1,6,1,5,1,4]
Explanation: [1,4,1,5,1,6] is also accepted.
def sorty(arra_nums):
    for i in range(len(arra_nums)):
        if (i%2 == 0) == (arra_nums[i-1] < arra_nums[i]):
            arra_nums[i-1],arra_nums[i] = arra_nums[i],arra_nums[i-1]
    return arra_nums



arr=list(map(int,input('Array_nums : ').split(' ')))
print(sorty(arr))

Input_1:
Array_nums : 1,5,1,1,6,4

Output:
[1, 4, 1, 5, 1, 6]


Input_2:
Array _nums: 1,3,2,2,3,1

Output:
[1, 2, 1, 3, 2, 3]



Input_3:
Array_nums : 1,4,3,4,1,2,1,3,1,3,2,3,3

Output:
[1, 4, 3, 4, 1, 2, 1, 3, 1, 3, 2, 3, 3]


Illustration of the code run/execution

Executed using terminal (Ubuntu) python3

More Q