Skip to content

Wiggle sort #2419

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 11 commits into from
Sep 25, 2020
28 changes: 20 additions & 8 deletions sorts/wiggle_sort.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,18 +9,30 @@
"""


def wiggle_sort(nums):
"""Perform Wiggle Sort."""
for i in range(len(nums)):
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):
if (i % 2 == 1) == (nums[i - 1] > nums[i]):
nums[i - 1], nums[i] = nums[i], nums[i - 1]

return nums


if __name__ == "__main__":
print("Enter the array elements:\n")
print("Enter the array elements:")
array = list(map(int, input().split()))
print("The unsorted array is:\n")
print(array)
wiggle_sort(array)
print("Array after Wiggle sort:\n")
print("The unsorted array is:")
print(array)
print("Array after Wiggle sort:")
print(wiggle_sort(array))