File tree Expand file tree Collapse file tree 1 file changed +21
-3
lines changed
src/main/java/com/thealgorithms/misc Expand file tree Collapse file tree 1 file changed +21
-3
lines changed Original file line number Diff line number Diff line change 17
17
* @author Rashi Dashore (https://github.com/rashi07dashore)
18
18
*/
19
19
public final class ShuffleArray {
20
- // Prevent instantiation
20
+
21
21
private ShuffleArray () {
22
22
}
23
23
24
24
/**
25
- * This method shuffles an array using the Fisher- Yates algorithm.
25
+ * Shuffles the provided array in-place using the Fisher– Yates algorithm.
26
26
*
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}
28
29
*/
29
30
public static void shuffle (int [] arr ) {
31
+ if (arr == null ) {
32
+ throw new IllegalArgumentException ("Input array must not be null" );
33
+ }
34
+
30
35
Random random = new Random ();
31
36
for (int i = arr .length - 1 ; i > 0 ; i --) {
32
37
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 ) {
33
51
int temp = arr [i ];
34
52
arr [i ] = arr [j ];
35
53
arr [j ] = temp ;
You can’t perform that action at this time.
0 commit comments