Advertisement
Iam_Sandeep

Wiggle Sort

Jul 18th, 2022
1,067
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.01 KB | None | 0 0
  1. '''
  2. This can be done in O(n) time by doing a single traversal of the given array. The idea is based on the fact that if we make sure that all even positioned (at index 0, 2, 4, ..) elements are greater than their adjacent odd elements, we don't need to worry about oddly positioned elements.
  3.  
  4. The following are simple steps.
  5. 1) Traverse all even positioned elements of the input array, and do the following.
  6. ....a) If the current element is smaller than the previous odd element, swap previous and current.
  7. ....b) If the current element is smaller than the next odd element, swap next and current.
  8. '''
  9. class Solution:
  10.     #Complete this function
  11.     #Function to sort the array into a wave-like array.
  12.     def convertToWave(self,arr,N):
  13.         for i in range(0,N,2):
  14.             if i-1>=0:
  15.                 if arr[i-1]>arr[i]:
  16.                     arr[i-1],arr[i]=arr[i],arr[i-1]
  17.             if i+1<=N-1:
  18.                 if arr[i]<arr[i+1]:
  19.                     arr[i],arr[i+1]=arr[i+1],arr[i]
  20.         return arr
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement