refactor ShuffleArray: improve documentation and maintainability (#6357)

refactor ShuffleArray: Improve Documentation and Code Quality
This commit is contained in:
Oleksandr Klymenko
2025-07-09 21:36:39 +03:00
committed by GitHub
parent 476898723a
commit c997a32018

View File

@@ -17,19 +17,37 @@ import java.util.Random;
* @author Rashi Dashore (https://github.com/rashi07dashore)
*/
public final class ShuffleArray {
// Prevent instantiation
private ShuffleArray() {
}
/**
* This method shuffles an array using the Fisher-Yates algorithm.
* Shuffles the provided array in-place using the FisherYates algorithm.
*
* @param arr is the input array to be shuffled
* @param arr the array to shuffle; must not be {@code null}
* @throws IllegalArgumentException if the input array is {@code null}
*/
public static void shuffle(int[] arr) {
if (arr == null) {
throw new IllegalArgumentException("Input array must not be null");
}
Random random = new Random();
for (int i = arr.length - 1; i > 0; i--) {
int j = random.nextInt(i + 1);
swap(arr, i, j);
}
}
/**
* Swaps two elements in an array.
*
* @param arr the array
* @param i index of first element
* @param j index of second element
*/
private static void swap(int[] arr, int i, int j) {
if (i != j) {
int temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;