Skip to content
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.

Commit 32481a3

Browse files
committedOct 2, 2024·
Wiggle sort changes (hacktoberfest Pull Request 2)
1 parent 6e73089 commit 32481a3

File tree

1 file changed

+14
-13
lines changed

1 file changed

+14
-13
lines changed
 

‎sorts/wiggle_sort.py

Lines changed: 14 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -1,18 +1,18 @@
11
"""
22
Wiggle Sort.
33
4-
Given an unsorted array nums, reorder it such
5-
that nums[0] < nums[1] > nums[2] < nums[3]....
4+
Given an unsorted array nums, reorder it such that:
5+
nums[0] < nums[1] > nums[2] < nums[3]....
6+
67
For example:
78
if input numbers = [3, 5, 2, 1, 6, 4]
8-
one possible Wiggle Sorted answer is [3, 5, 1, 6, 2, 4].
9+
One possible Wiggle Sorted answer is [3, 5, 1, 6, 2, 4].
910
"""
1011

11-
1212
def wiggle_sort(nums: list) -> list:
1313
"""
14-
Python implementation of wiggle.
15-
Example:
14+
Python implementation of Wiggle Sort.
15+
1616
>>> wiggle_sort([0, 5, 3, 2, 2])
1717
[0, 5, 2, 3, 2]
1818
>>> wiggle_sort([])
@@ -22,17 +22,18 @@ def wiggle_sort(nums: list) -> list:
2222
>>> wiggle_sort([-2.1, -5.68, -45.11])
2323
[-45.11, -2.1, -5.68]
2424
"""
25-
for i, _ in enumerate(nums):
25+
for i in range(1, len(nums)):
2626
if (i % 2 == 1) == (nums[i - 1] > nums[i]):
2727
nums[i - 1], nums[i] = nums[i], nums[i - 1]
2828

2929
return nums
3030

3131

3232
if __name__ == "__main__":
33-
print("Enter the array elements:")
34-
array = list(map(int, input().split()))
35-
print("The unsorted array is:")
36-
print(array)
37-
print("Array after Wiggle sort:")
38-
print(wiggle_sort(array))
33+
try:
34+
user_input = input("Enter the array elements (space-separated integers):\n").strip()
35+
array = list(map(int, user_input.split()))
36+
print("The unsorted array is:", array)
37+
print("Array after Wiggle sort:", wiggle_sort(array))
38+
except ValueError:
39+
print("Error: Please enter valid integers.")

0 commit comments

Comments
 (0)
Please sign in to comment.