Wiggle sort (#2419)

* wiggle sort : type hint + doctest

* fixed function name in docstring

* correction
This commit is contained in:
Guillaume Rochedix 2020-09-25 09:18:00 +02:00 committed by GitHub
parent 08eb1efafe
commit f564c9d7c6
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23

View File

@ -9,18 +9,30 @@ one possible Wiggle Sorted answer is [3, 5, 1, 6, 2, 4].
""" """
def wiggle_sort(nums): def wiggle_sort(nums: list) -> list:
"""Perform Wiggle Sort.""" """
for i in range(len(nums)): 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]): if (i % 2 == 1) == (nums[i - 1] > nums[i]):
nums[i - 1], nums[i] = nums[i], nums[i - 1] nums[i - 1], nums[i] = nums[i], nums[i - 1]
return nums
if __name__ == "__main__": if __name__ == "__main__":
print("Enter the array elements:\n") print("Enter the array elements:")
array = list(map(int, input().split())) array = list(map(int, input().split()))
print("The unsorted array is:\n") print("The unsorted array is:")
print(array)
wiggle_sort(array)
print("Array after Wiggle sort:\n")
print(array) print(array)
print("Array after Wiggle sort:")
print(wiggle_sort(array))