I am solving interview questions from here.
Problem : Given an array of integers, sort the array into a wave like array and return it, in other words, arrange the elements into a sequence such that a1 >= a2 <= a3 >= a4 <= a5.
Note - If there are multiple answers possible than return the one that is lexicographically smallest.
Approach : First sort the array then swap every second number with previous number.
This is my solution:
def wave(array): """Returns array in wave pattern by first sorting the array and then swapping the adjacent digits""" array.sort() ##sort the given array for i in range(0,(len(array)-1),2): ##skip every second number array[i], array[i+1] = array[i+1], array[i] ##swap adjacent numbers return array print wave([6,7,8,1,2,3,4]) print wave([5,1,3,4,2]) print wave([11,3,5,2,7,1,6,8,10,9,4])
How can i make this code better? Is there any other approach to solve this problem?