From 11c1726492ec8990d5bad07aecc5271687f353f3 Mon Sep 17 00:00:00 2001 From: Rishavbhattarai Date: Mon, 26 Oct 2026 19:23:42 -0700 Subject: [PATCH] fix(sorts): stop SwapSort looping forever on duplicate values --- src/main/java/com/thealgorithms/sorts/SwapSort.java | 7 ++++++- .../java/com/thealgorithms/sorts/SwapSortTest.java | 13 +++++++++++++ 2 files changed, 19 insertions(+), 1 deletion(-) diff --git a/src/main/java/com/thealgorithms/sorts/SwapSort.java b/src/main/java/com/thealgorithms/sorts/SwapSort.java index b5c1c3892546..169fba93fc57 100644 --- a/src/main/java/com/thealgorithms/sorts/SwapSort.java +++ b/src/main/java/com/thealgorithms/sorts/SwapSort.java @@ -17,7 +17,12 @@ public > T[] sort(T[] array) { final int amountSmallerElements = this.getSmallerElementCount(array, index); if (amountSmallerElements > 0) { - SortUtils.swap(array, index, index + amountSmallerElements); + int target = index + amountSmallerElements; + // Skip slots that already hold an equal element, otherwise two equal values swap forever + while (array[target].compareTo(array[index]) == 0) { + target++; + } + SortUtils.swap(array, index, target); } else { index++; } diff --git a/src/test/java/com/thealgorithms/sorts/SwapSortTest.java b/src/test/java/com/thealgorithms/sorts/SwapSortTest.java index c1638a385940..e29bbc5f1b64 100644 --- a/src/test/java/com/thealgorithms/sorts/SwapSortTest.java +++ b/src/test/java/com/thealgorithms/sorts/SwapSortTest.java @@ -1,8 +1,21 @@ package com.thealgorithms.sorts; +import static org.junit.jupiter.api.Assertions.assertArrayEquals; + +import java.util.concurrent.TimeUnit; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.Timeout; + public class SwapSortTest extends SortingAlgorithmTest { @Override SortAlgorithm getSortAlgorithm() { return new SwapSort(); } + + @Test + @Timeout(value = 1, unit = TimeUnit.SECONDS, threadMode = Timeout.ThreadMode.SEPARATE_THREAD) + void shouldSortWhenDuplicateWouldBeSwappedOntoItsTwin() { + Integer[] array = {2, 2, 1, 1, 0, 0, 0}; + assertArrayEquals(new Integer[] {0, 0, 0, 1, 1, 2, 2}, new SwapSort().sort(array)); + } }