|
| 1 | +package com.thealgorithms.misc; |
| 2 | +import java.util.Random; |
| 3 | +import java.util.Scanner; |
| 4 | +/** |
| 5 | + * The Fisher-Yates (Knuth) Shuffle algorithm randomly permutes an array's |
| 6 | + * elements, ensuring each permutation is equally likely. |
| 7 | + * |
| 8 | + * <p> |
| 9 | + * Worst-case performance O(n) |
| 10 | + * Best-case performance O(n) |
| 11 | + * Average performance O(n) |
| 12 | + * Worst-case space complexity O(1) |
| 13 | + * |
| 14 | + * This class provides a static method to shuffle an array in place. |
| 15 | + * |
| 16 | + * @author Your Name (https://github.com/Chiefpatwal) |
| 17 | + */ |
| 18 | +public final class ShuffleArray { |
| 19 | + // Prevent instantiation |
| 20 | + private ShuffleArray() { |
| 21 | + } |
| 22 | + /** |
| 23 | + * This method shuffles an array using the Fisher-Yates algorithm. |
| 24 | + * |
| 25 | + * @param arr is the input array to be shuffled |
| 26 | + */ |
| 27 | + public static void shuffle(int[] arr) { |
| 28 | + Random random = new Random(); |
| 29 | + for (int i = arr.length - 1; i > 0; i--) { |
| 30 | + int j = random.nextInt(i + 1); |
| 31 | + int temp = arr[i]; |
| 32 | + arr[i] = arr[j]; |
| 33 | + arr[j] = temp; |
| 34 | + } |
| 35 | + } |
| 36 | + /** |
| 37 | + * This method takes user input to create an array. |
| 38 | + * |
| 39 | + * @return the array created from user input |
| 40 | + */ |
| 41 | + public static int[] getUserInputArray() { |
| 42 | + Scanner scanner = new Scanner(System.in); |
| 43 | + System.out.print("Enter the size of the array: "); |
| 44 | + int size = scanner.nextInt(); |
| 45 | + |
| 46 | + int[] arr = new int[size]; |
| 47 | + System.out.println("Enter " + size + " elements:"); |
| 48 | + for (int i = 0; i < size; i++) { |
| 49 | + arr[i] = scanner.nextInt(); |
| 50 | + } |
| 51 | + return arr; |
| 52 | + } |
| 53 | + public static void main(String[] args) { |
| 54 | + int[] userArray = getUserInputArray(); |
| 55 | + System.out.println("Original Array:"); |
| 56 | + printArray(userArray); |
| 57 | + |
| 58 | + shuffle(userArray); |
| 59 | + System.out.println("Shuffled Array:"); |
| 60 | + printArray(userArray); |
| 61 | + } |
| 62 | + /** |
| 63 | + * This method prints the elements of the array. |
| 64 | + * |
| 65 | + * @param arr is the input array to be printed |
| 66 | + */ |
| 67 | + public static void printArray(int[] arr) { |
| 68 | + for (int num : arr) { |
| 69 | + System.out.print(num + " "); |
| 70 | + } |
| 71 | + System.out.println(); |
| 72 | + } |
| 73 | +} |
0 commit comments