Skip to content

Commit 758df7d

Browse files
alxkmvil02
andauthored
feat: optimize SortUtils.swap by skipping operations for equal indices (#5266)
* Refactor: adding check to swap method in SortUtils * Checkstyle: fix formatting * Checkstyle: fix formatting, and redundant braces * fix: adding flipped tests, removed messages from tests * checkstyle: fix indent * style: mark `temp` as `final` * tests: remove test case with empty array Such calls should be excluded. --------- Co-authored-by: Piotr Idzik <[email protected]>
1 parent 20e7a3a commit 758df7d

File tree

2 files changed

+29
-3
lines changed

2 files changed

+29
-3
lines changed

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

+5-3
Original file line numberDiff line numberDiff line change
@@ -17,9 +17,11 @@ private SortUtils() {
1717
* @param <T> the type of elements in the array
1818
*/
1919
public static <T> void swap(T[] array, int i, int j) {
20-
T temp = array[i];
21-
array[i] = array[j];
22-
array[j] = temp;
20+
if (i != j) {
21+
final T temp = array[i];
22+
array[i] = array[j];
23+
array[j] = temp;
24+
}
2325
}
2426

2527
/**

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

+24
Original file line numberDiff line numberDiff line change
@@ -1,10 +1,15 @@
11
package com.thealgorithms.sorts;
22

3+
import static org.junit.jupiter.api.Assertions.assertArrayEquals;
34
import static org.junit.jupiter.api.Assertions.assertFalse;
45
import static org.junit.jupiter.api.Assertions.assertTrue;
56

67
import java.util.List;
8+
import java.util.stream.Stream;
79
import org.junit.jupiter.api.Test;
10+
import org.junit.jupiter.params.ParameterizedTest;
11+
import org.junit.jupiter.params.provider.Arguments;
12+
import org.junit.jupiter.params.provider.MethodSource;
813

914
class SortUtilsTest {
1015

@@ -67,4 +72,23 @@ void isSortedListFalse() {
6772
List<Integer> array3 = List.of(5, 4, 3, 2, 1);
6873
assertFalse(SortUtils.isSorted(array3));
6974
}
75+
76+
@ParameterizedTest
77+
@MethodSource("provideArraysForSwap")
78+
public <T> void testSwap(T[] array, int i, int j, T[] expected) {
79+
SortUtils.swap(array, i, j);
80+
assertArrayEquals(expected, array);
81+
}
82+
83+
@ParameterizedTest
84+
@MethodSource("provideArraysForSwap")
85+
public <T> void testSwapFlippedIndices(T[] array, int i, int j, T[] expected) {
86+
SortUtils.swap(array, j, i);
87+
assertArrayEquals(expected, array);
88+
}
89+
90+
private static Stream<Arguments> provideArraysForSwap() {
91+
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}),
92+
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}));
93+
}
7094
}

0 commit comments

Comments
 (0)