Skip to content
Closed
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
18 changes: 17 additions & 1 deletion sorts/wiggle_sort.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,8 +8,18 @@
one possible Wiggle Sorted answer is [3, 5, 1, 6, 2, 4].
"""

from __future__ import annotations

def wiggle_sort(nums: list) -> list:
from typing import Any, Protocol


class Comparable(Protocol):
def __lt__(self, other: Any, /) -> bool: ...

def __gt__(self, other: Any, /) -> bool: ...


def wiggle_sort[T: Comparable](nums: list[T]) -> list[T]:
"""
Python implementation of wiggle sort.
Reorders an array such that nums[0] <= nums[1] >= nums[2] <= nums[3]...
Expand All @@ -23,6 +33,12 @@ def wiggle_sort(nums: list) -> list:
[-5, -2, -45]
>>> wiggle_sort([-2.1, -5.68, -45.11])
[-5.68, -2.1, -45.11]
>>> wiggle_sort(["d", "a", "c", "b"])
['a', 'd', 'b', 'c']
>>> wiggle_sort([1, "a"])
Traceback (most recent call last):
...
TypeError: '>' not supported between instances of 'int' and 'str'
"""
for i in range(1, len(nums)):
if (i % 2 == 1 and nums[i - 1] > nums[i]) or (
Expand Down
Loading