Commit e727f36
authored
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.1 parent c6012e3 commit e727f36
1 file changed
Lines changed: 7 additions & 3 deletions
| Original file line number | Diff line number | Diff line change | |
|---|---|---|---|
| |||
11 | 11 | | |
12 | 12 | | |
13 | 13 | | |
14 | | - | |
| 14 | + | |
| 15 | + | |
| 16 | + | |
15 | 17 | | |
16 | 18 | | |
17 | 19 | | |
| |||
22 | 24 | | |
23 | 25 | | |
24 | 26 | | |
25 | | - | |
26 | | - | |
| 27 | + | |
| 28 | + | |
| 29 | + | |
| 30 | + | |
27 | 31 | | |
28 | 32 | | |
29 | 33 | | |
| |||
0 commit comments