Skip to content

Commit 343dfc9

Browse files
committed
docs: correct stale WiggleSort Javadoc about undetected inputs
The class Javadoc claimed [1, 2, 2] slips through undetected, but the odd-array median guard added later in wiggleSort() already catches exactly that case and throws IllegalArgumentException. Update the Javadoc to describe the current behavior and add regression tests asserting that [1, 2, 2] and arrays with too many duplicates throw instead of returning a wrongly ordered result. Fixes #7507
1 parent 12aab70 commit 343dfc9

2 files changed

Lines changed: 22 additions & 3 deletions

File tree

src/main/java/com/thealgorithms/sorts/WiggleSort.java

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -11,9 +11,9 @@
1111
* https://cs.stackexchange.com/questions/125372/how-to-wiggle-sort-an-array-in-linear-time-complexity
1212
* Also have a look at:
1313
* https://cs.stackexchange.com/questions/125372/how-to-wiggle-sort-an-array-in-linear-time-complexity?noredirect=1&lq=1
14-
* Not all arrays are wiggle-sortable. This algorithm will find some obviously not wiggle-sortable
15-
* arrays and throw an error, but there are some exceptions that won't be caught, for example [1, 2,
16-
* 2].
14+
* Not all arrays are wiggle-sortable. This algorithm detects non-wiggle-sortable inputs — for
15+
* example [1, 2, 2], or arrays where more than half the values are equal — and throws an
16+
* IllegalArgumentException instead of returning a wrongly ordered result.
1717
*/
1818
public class WiggleSort implements SortAlgorithm {
1919

src/test/java/com/thealgorithms/sorts/WiggleSortTest.java

Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
11
package com.thealgorithms.sorts;
22

33
import static org.junit.jupiter.api.Assertions.assertArrayEquals;
4+
import static org.junit.jupiter.api.Assertions.assertThrows;
45

56
import java.util.Arrays;
67
import org.junit.jupiter.api.Test;
@@ -70,4 +71,22 @@ void wiggleTestStrings() {
7071
wiggleSort.sort(values);
7172
assertArrayEquals(values, result);
7273
}
74+
75+
@Test
76+
void wiggleTestNonWiggleSortableOddArrayThrows() {
77+
// [1, 2, 2] is not wiggle-sortable: the median 2 appears ceil(3 / 2) = 2 times
78+
// but is not the smallest value, so sorting must fail instead of returning
79+
// a wrongly ordered array
80+
WiggleSort wiggleSort = new WiggleSort();
81+
Integer[] values = {1, 2, 2};
82+
assertThrows(IllegalArgumentException.class, () -> wiggleSort.sort(values));
83+
}
84+
85+
@Test
86+
void wiggleTestTooManyDuplicatesThrows() {
87+
// more than half of the values are the same, which can never be wiggle-sorted
88+
WiggleSort wiggleSort = new WiggleSort();
89+
Integer[] values = {2, 2, 2, 1};
90+
assertThrows(IllegalArgumentException.class, () -> wiggleSort.sort(values));
91+
}
7392
}

0 commit comments

Comments
 (0)