Skip to content

refactor ShuffleArray: improve documentation and maintainability #6357

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 1 commit into from
Jul 9, 2025
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
24 changes: 21 additions & 3 deletions src/main/java/com/thealgorithms/misc/ShuffleArray.java
Original file line number Diff line number Diff line change
Expand Up @@ -17,19 +17,37 @@
* @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;
Expand Down
Loading