diff --git a/src/main/java/com/thealgorithms/misc/ShuffleArray.java b/src/main/java/com/thealgorithms/misc/ShuffleArray.java index 65d38adfc37a..e07c8df771d3 100644 --- a/src/main/java/com/thealgorithms/misc/ShuffleArray.java +++ b/src/main/java/com/thealgorithms/misc/ShuffleArray.java @@ -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 Fisher–Yates 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; 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