1
1
"""
2
2
Wiggle Sort.
3
3
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
+
6
7
For example:
7
8
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].
9
10
"""
10
11
11
-
12
12
def wiggle_sort (nums : list ) -> list :
13
13
"""
14
- Python implementation of wiggle .
15
- Example:
14
+ Python implementation of Wiggle Sort .
15
+
16
16
>>> wiggle_sort([0, 5, 3, 2, 2])
17
17
[0, 5, 2, 3, 2]
18
18
>>> wiggle_sort([])
@@ -22,17 +22,18 @@ def wiggle_sort(nums: list) -> list:
22
22
>>> wiggle_sort([-2.1, -5.68, -45.11])
23
23
[-45.11, -2.1, -5.68]
24
24
"""
25
- for i , _ in enumerate ( nums ):
25
+ for i in range ( 1 , len ( nums ) ):
26
26
if (i % 2 == 1 ) == (nums [i - 1 ] > nums [i ]):
27
27
nums [i - 1 ], nums [i ] = nums [i ], nums [i - 1 ]
28
28
29
29
return nums
30
30
31
31
32
32
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