Skip to content

Commit c997a32

Browse files
authored
refactor ShuffleArray: improve documentation and maintainability (#6357)
refactor ShuffleArray: Improve Documentation and Code Quality
1 parent 4768987 commit c997a32

File tree

1 file changed

+21
-3
lines changed

1 file changed

+21
-3
lines changed

src/main/java/com/thealgorithms/misc/ShuffleArray.java

Lines changed: 21 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -17,19 +17,37 @@
1717
* @author Rashi Dashore (https://github.com/rashi07dashore)
1818
*/
1919
public final class ShuffleArray {
20-
// Prevent instantiation
20+
2121
private ShuffleArray() {
2222
}
2323

2424
/**
25-
* This method shuffles an array using the Fisher-Yates algorithm.
25+
* Shuffles the provided array in-place using the FisherYates algorithm.
2626
*
27-
* @param arr is the input array to be shuffled
27+
* @param arr the array to shuffle; must not be {@code null}
28+
* @throws IllegalArgumentException if the input array is {@code null}
2829
*/
2930
public static void shuffle(int[] arr) {
31+
if (arr == null) {
32+
throw new IllegalArgumentException("Input array must not be null");
33+
}
34+
3035
Random random = new Random();
3136
for (int i = arr.length - 1; i > 0; i--) {
3237
int j = random.nextInt(i + 1);
38+
swap(arr, i, j);
39+
}
40+
}
41+
42+
/**
43+
* Swaps two elements in an array.
44+
*
45+
* @param arr the array
46+
* @param i index of first element
47+
* @param j index of second element
48+
*/
49+
private static void swap(int[] arr, int i, int j) {
50+
if (i != j) {
3351
int temp = arr[i];
3452
arr[i] = arr[j];
3553
arr[j] = temp;

0 commit comments

Comments
 (0)
pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy