Menu Close

Reorder array such that arr[0] <= arr[1] >= arr[2] ….arr[n].

Given an unsorted array nums, reorder it in-place such that nums[0] <= nums[1] >= nums[2] <= nums[3]….

Input: [20,10,8,6,4,2]

Output:[2,10,6,8,4,20]
def sorty(arra_nums):
    for i in range(len(arra_nums)):
        if (i%2 == 1) == (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(' '))) #or arr=[20,10,8,6,4,2]
print(sorty(arr))

Input_1:
Array_nums : 20 10 8 6 4 2
Output:
[2, 10, 6, 8, 4, 20]


Input_2:
Array_nums : 10 5 6 3 2 20 100 80
Output:
[5, 10, 3, 6, 2, 100, 20, 80]


Input_3:
Array_nums : 3 6 5 10 7 10
Output:
[3, 6, 5, 10, 7, 10]


Input_4:
Array_nums : 6 3 10 5 20 7
Output:
[3, 10, 5, 20, 6, 7]


Illustration of the Output:

Executed using python3

More Q