w3resource

Python: Sort an unsorted array numbers using Wiggle sort

Python Search and Sorting: Exercise-24 with Solution

Write a Python program to sort an unsorted array of numbers using Wiggle sort.

Wiggle Sort:
Given an unsorted array nums, reorder it in-place such that nums[0] <= nums[1] >= nums[2] <= nums[3]....
For example, given nums = [3, 5, 2, 1, 6, 4], one possible answer is [1, 6, 2, 5, 3, 4].

Sample Solution:

Python Code:

def wiggle_sort(arra_nums):
    for i, _ in enumerate(arra_nums):
        if (i % 2 == 1) == (arra_nums[i - 1] > arra_nums[i]):
            arra_nums[i - 1], arra_nums[i] = arra_nums[i], arra_nums[i - 1]

    return arra_nums

print("Input the array elements: ")
arra_nums = list(map(int, input().split()))
print("Original unsorted array:")
print(arra_nums)
print("The said array after applying Wiggle sort:")
print(wiggle_sort(arra_nums))

Sample Output:

Input the array elements: 
 1 5 2 3 4 6
Original unsorted array:
[1, 5, 2, 3, 4, 6]
The said array after applying Wiggle sort:
[1, 5, 2, 4, 3, 6]

Flowchart:

Flowchart: Python Data Structures and Algorithms: Sort an unsorted array numbers using Wiggle sort

Python Code Editor:

Contribute your code and comments through Disqus.

Previous: Write a Python program to sort a list of elements using Tree sort.
Next: Write a Python program to sort unsorted numbers using Timsort.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Become a Patron!

Follow us on Facebook and Twitter for latest update.

It will be nice if you may share this link in any developer community or anywhere else, from where other developers may find this content. Thanks.

https://198.211.115.131/python-exercises/data-structures-and-algorithms/python-search-and-sorting-exercise-24.php