diff --git a/src/main/java/com/thealgorithms/sorts/SortUtils.java b/src/main/java/com/thealgorithms/sorts/SortUtils.java index fda19751..9e51c3d9 100644 --- a/src/main/java/com/thealgorithms/sorts/SortUtils.java +++ b/src/main/java/com/thealgorithms/sorts/SortUtils.java @@ -17,9 +17,11 @@ final class SortUtils { * @param the type of elements in the array */ public static void swap(T[] array, int i, int j) { - T temp = array[i]; - array[i] = array[j]; - array[j] = temp; + if (i != j) { + final T temp = array[i]; + array[i] = array[j]; + array[j] = temp; + } } /** diff --git a/src/test/java/com/thealgorithms/sorts/SortUtilsTest.java b/src/test/java/com/thealgorithms/sorts/SortUtilsTest.java index 591b5389..ac654148 100644 --- a/src/test/java/com/thealgorithms/sorts/SortUtilsTest.java +++ b/src/test/java/com/thealgorithms/sorts/SortUtilsTest.java @@ -1,10 +1,15 @@ package com.thealgorithms.sorts; +import static org.junit.jupiter.api.Assertions.assertArrayEquals; import static org.junit.jupiter.api.Assertions.assertFalse; import static org.junit.jupiter.api.Assertions.assertTrue; import java.util.List; +import java.util.stream.Stream; import org.junit.jupiter.api.Test; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.Arguments; +import org.junit.jupiter.params.provider.MethodSource; class SortUtilsTest { @@ -67,4 +72,23 @@ class SortUtilsTest { List array3 = List.of(5, 4, 3, 2, 1); assertFalse(SortUtils.isSorted(array3)); } + + @ParameterizedTest + @MethodSource("provideArraysForSwap") + public void testSwap(T[] array, int i, int j, T[] expected) { + SortUtils.swap(array, i, j); + assertArrayEquals(expected, array); + } + + @ParameterizedTest + @MethodSource("provideArraysForSwap") + public void testSwapFlippedIndices(T[] array, int i, int j, T[] expected) { + SortUtils.swap(array, j, i); + assertArrayEquals(expected, array); + } + + private static Stream provideArraysForSwap() { + return Stream.of(Arguments.of(new Integer[] {1, 2, 3, 4}, 1, 2, new Integer[] {1, 3, 2, 4}), Arguments.of(new Integer[] {1, 2, 3, 4}, 0, 3, new Integer[] {4, 2, 3, 1}), Arguments.of(new Integer[] {1, 2, 3, 4}, 2, 2, new Integer[] {1, 2, 3, 4}), + Arguments.of(new String[] {"a", "b", "c", "d"}, 0, 3, new String[] {"d", "b", "c", "a"}), Arguments.of(new String[] {null, "b", "c", null}, 0, 3, new String[] {null, "b", "c", null})); + } }