2019-03-17 18:12:22 +00:00
|
|
|
"""
|
2019-07-01 08:10:18 +00:00
|
|
|
Wiggle Sort.
|
|
|
|
|
|
|
|
Given an unsorted array nums, reorder it such
|
|
|
|
that nums[0] < nums[1] > nums[2] < nums[3]....
|
2019-03-17 18:12:22 +00:00
|
|
|
For example:
|
2019-07-01 08:10:18 +00:00
|
|
|
if input numbers = [3, 5, 2, 1, 6, 4]
|
2019-03-17 18:12:22 +00:00
|
|
|
one possible Wiggle Sorted answer is [3, 5, 1, 6, 2, 4].
|
|
|
|
"""
|
2019-07-01 08:10:18 +00:00
|
|
|
|
|
|
|
|
2020-09-25 07:18:00 +00:00
|
|
|
def wiggle_sort(nums: list) -> list:
|
|
|
|
"""
|
|
|
|
Python implementation of wiggle.
|
|
|
|
Example:
|
|
|
|
>>> wiggle_sort([0, 5, 3, 2, 2])
|
|
|
|
[0, 5, 2, 3, 2]
|
|
|
|
>>> wiggle_sort([])
|
|
|
|
[]
|
|
|
|
>>> wiggle_sort([-2, -5, -45])
|
|
|
|
[-45, -2, -5]
|
|
|
|
>>> wiggle_sort([-2.1, -5.68, -45.11])
|
|
|
|
[-45.11, -2.1, -5.68]
|
|
|
|
"""
|
|
|
|
for i, _ in enumerate(nums):
|
2019-07-01 08:10:18 +00:00
|
|
|
if (i % 2 == 1) == (nums[i - 1] > nums[i]):
|
|
|
|
nums[i - 1], nums[i] = nums[i], nums[i - 1]
|
|
|
|
|
2020-09-25 07:18:00 +00:00
|
|
|
return nums
|
|
|
|
|
2019-03-17 18:12:22 +00:00
|
|
|
|
2019-10-05 05:14:13 +00:00
|
|
|
if __name__ == "__main__":
|
2020-09-25 07:18:00 +00:00
|
|
|
print("Enter the array elements:")
|
2019-07-01 08:10:18 +00:00
|
|
|
array = list(map(int, input().split()))
|
2020-09-25 07:18:00 +00:00
|
|
|
print("The unsorted array is:")
|
2019-05-25 13:41:24 +00:00
|
|
|
print(array)
|
2020-09-25 07:18:00 +00:00
|
|
|
print("Array after Wiggle sort:")
|
|
|
|
print(wiggle_sort(array))
|