Skip to content
Merged
Show file tree
Hide file tree
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
6 changes: 3 additions & 3 deletions src/main/java/com/thealgorithms/sorts/WiggleSort.java
Original file line number Diff line number Diff line change
Expand Up @@ -11,9 +11,9 @@
* https://cs.stackexchange.com/questions/125372/how-to-wiggle-sort-an-array-in-linear-time-complexity
* Also have a look at:
* https://cs.stackexchange.com/questions/125372/how-to-wiggle-sort-an-array-in-linear-time-complexity?noredirect=1&lq=1
* Not all arrays are wiggle-sortable. This algorithm will find some obviously not wiggle-sortable
* arrays and throw an error, but there are some exceptions that won't be caught, for example [1, 2,
* 2].
* Not all arrays are wiggle-sortable. This algorithm detects non-wiggle-sortable inputs — for
* example [1, 2, 2], or arrays where more than half the values are equal — and throws an
* IllegalArgumentException instead of returning a wrongly ordered result.
*/
public class WiggleSort implements SortAlgorithm {

Expand Down
19 changes: 19 additions & 0 deletions src/test/java/com/thealgorithms/sorts/WiggleSortTest.java
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
package com.thealgorithms.sorts;

import static org.junit.jupiter.api.Assertions.assertArrayEquals;
import static org.junit.jupiter.api.Assertions.assertThrows;

import java.util.Arrays;
import org.junit.jupiter.api.Test;
Expand Down Expand Up @@ -70,4 +71,22 @@ void wiggleTestStrings() {
wiggleSort.sort(values);
assertArrayEquals(values, result);
}

@Test
void wiggleTestNonWiggleSortableOddArrayThrows() {
// [1, 2, 2] is not wiggle-sortable: the median 2 appears ceil(3 / 2) = 2 times
// but is not the smallest value, so sorting must fail instead of returning
// a wrongly ordered array
WiggleSort wiggleSort = new WiggleSort();
Integer[] values = {1, 2, 2};
assertThrows(IllegalArgumentException.class, () -> wiggleSort.sort(values));
}

@Test
void wiggleTestTooManyDuplicatesThrows() {
// more than half of the values are the same, which can never be wiggle-sorted
WiggleSort wiggleSort = new WiggleSort();
Integer[] values = {2, 2, 2, 1};
assertThrows(IllegalArgumentException.class, () -> wiggleSort.sort(values));
}
}
Loading