Skip to content

Commit 6f19dd4

Browse files
fix(sorts): stop SwapSort looping forever on duplicate values (#7660)
Co-authored-by: Oleksandr Klymenko <19151554+alxkm@users.noreply.github.com>
1 parent 12f69b3 commit 6f19dd4

2 files changed

Lines changed: 19 additions & 1 deletion

File tree

‎src/main/java/com/thealgorithms/sorts/SwapSort.java‎

Lines changed: 6 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -17,7 +17,12 @@ public <T extends Comparable<T>> T[] sort(T[] array) {
1717
final int amountSmallerElements = this.getSmallerElementCount(array, index);
1818

1919
if (amountSmallerElements > 0) {
20-
SortUtils.swap(array, index, index + amountSmallerElements);
20+
int target = index + amountSmallerElements;
21+
// Skip slots that already hold an equal element, otherwise two equal values swap forever
22+
while (array[target].compareTo(array[index]) == 0) {
23+
target++;
24+
}
25+
SortUtils.swap(array, index, target);
2126
} else {
2227
index++;
2328
}
Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,8 +1,21 @@
11
package com.thealgorithms.sorts;
22

3+
import static org.junit.jupiter.api.Assertions.assertArrayEquals;
4+
5+
import java.util.concurrent.TimeUnit;
6+
import org.junit.jupiter.api.Test;
7+
import org.junit.jupiter.api.Timeout;
8+
39
public class SwapSortTest extends SortingAlgorithmTest {
410
@Override
511
SortAlgorithm getSortAlgorithm() {
612
return new SwapSort();
713
}
14+
15+
@Test
16+
@Timeout(value = 1, unit = TimeUnit.SECONDS, threadMode = Timeout.ThreadMode.SEPARATE_THREAD)
17+
void shouldSortWhenDuplicateWouldBeSwappedOntoItsTwin() {
18+
Integer[] array = {2, 2, 1, 1, 0, 0, 0};
19+
assertArrayEquals(new Integer[] {0, 0, 0, 1, 1, 2, 2}, new SwapSort().sort(array));
20+
}
821
}

0 commit comments

Comments
 (0)