Skip to content

Commit b0e607a

Browse files
Fix negative indexing bug and improve readability in wiggle_sort (#15371)
* Fix negative indexing bug and improve readability in wiggle_sort Issue: - The previous implementation used `enumerate(nums)`, starting the loop at `i = 0`. This caused `nums[i - 1]` to evaluate to `nums[-1]`, accidentally comparing (and potentially swapping) the first element with the last element of the array on the first iteration. - The conditional logic `(i % 2 == 1) == (nums[i - 1] > nums[i])` was convoluted, hard to read, and triggered unnecessary swaps when adjacent numbers were equal. Fix: - Changed the loop to use `range(1, len(nums))` to ensure the index safely starts at 1, eliminating the negative indexing bug. - Replaced the confusing equality check with explicit `if/elif` statements that clearly define the peak (odd indices) and valley (even indices) requirements of a Wiggle Sort. - Preserved all original docstrings and the __main__ block as-is. * [pre-commit.ci] auto fixes from pre-commit.com hooks for more information, see https://pre-commit.ci * Combine conditional branches to satisfy ruff linting - Updated `wiggle_sort` logic to merge the odd and even swap conditions using a single `or` expression. - Fixes SIM114 ruff linter check failure (`Combine if branches using logical or operator`). * [pre-commit.ci] auto fixes from pre-commit.com hooks for more information, see https://pre-commit.ci * Update doctests in wiggle_sort to match fixed implementation output - Updated expected outputs for negative array doctests in `sorts/wiggle_sort.py`. - The previous doctest expectations relied on the incorrect behavior caused by the index-0 negative lookup bug. - Fixes pytest doctest mismatch failure in CI build job. --------- Co-authored-by: pre-commit-ci[bot] <66853113+pre-commit-ci[bot]@users.noreply.github.com>
1 parent e7015a7 commit b0e607a

1 file changed

Lines changed: 9 additions & 5 deletions

File tree

‎sorts/wiggle_sort.py‎

Lines changed: 9 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -11,19 +11,23 @@
1111

1212
def wiggle_sort(nums: list) -> list:
1313
"""
14-
Python implementation of wiggle.
14+
Python implementation of wiggle sort.
15+
Reorders an array such that nums[0] <= nums[1] >= nums[2] <= nums[3]...
16+
1517
Example:
1618
>>> wiggle_sort([0, 5, 3, 2, 2])
1719
[0, 5, 2, 3, 2]
1820
>>> wiggle_sort([])
1921
[]
2022
>>> wiggle_sort([-2, -5, -45])
21-
[-45, -2, -5]
23+
[-5, -2, -45]
2224
>>> wiggle_sort([-2.1, -5.68, -45.11])
23-
[-45.11, -2.1, -5.68]
25+
[-5.68, -2.1, -45.11]
2426
"""
25-
for i, _ in enumerate(nums):
26-
if (i % 2 == 1) == (nums[i - 1] > nums[i]):
27+
for i in range(1, len(nums)):
28+
if (i % 2 == 1 and nums[i - 1] > nums[i]) or (
29+
i % 2 == 0 and nums[i - 1] < nums[i]
30+
):
2731
nums[i - 1], nums[i] = nums[i], nums[i - 1]
2832

2933
return nums

0 commit comments

Comments
 (0)