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 1717 * @author Rashi Dashore (https://github.com/rashi07dashore)
1818 */
1919public 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 Fisher– Yates 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 ;
You can’t perform that action at this time.
0 commit comments