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 <65706193+vil02@users.noreply.github.com>
This commit is contained in:
Alex Klymenko 2024-06-29 23:33:40 +03:00 committed by GitHub
parent 20e7a3aca4
commit 758df7dcc3
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
2 changed files with 29 additions and 3 deletions

View File

@ -17,10 +17,12 @@ final class SortUtils {
* @param <T> the type of elements in the array
*/
public static <T> void swap(T[] array, int i, int j) {
T temp = array[i];
if (i != j) {
final T temp = array[i];
array[i] = array[j];
array[j] = temp;
}
}
/**
* Compares two elements to see if the first is less than the second.

View File

@ -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<Integer> array3 = List.of(5, 4, 3, 2, 1);
assertFalse(SortUtils.isSorted(array3));
}
@ParameterizedTest
@MethodSource("provideArraysForSwap")
public <T> void testSwap(T[] array, int i, int j, T[] expected) {
SortUtils.swap(array, i, j);
assertArrayEquals(expected, array);
}
@ParameterizedTest
@MethodSource("provideArraysForSwap")
public <T> void testSwapFlippedIndices(T[] array, int i, int j, T[] expected) {
SortUtils.swap(array, j, i);
assertArrayEquals(expected, array);
}
private static Stream<Arguments> 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}));
}
}