Advertisement
Darkness4869

TheFisherYatesAlgorithm.java

Sep 11th, 2020
88
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.40 KB | None | 0 0
  1. // Folder directory of TheFisherYatesAlgorithm.java
  2. package Question8;
  3. // Importing Random
  4. import java.util.Random;
  5. // Importing Arrays
  6. import java.util.Arrays;
  7. // The Fisher Yates Algorithm class
  8. public class TheFisherYatesAlgorithm {
  9.     // Randomize method
  10.     public static void randomize(int[] array, int lengthArray) {
  11.         // Instantiating Stray object from Random class.
  12.         Random Stray = new Random();
  13.         // Loop to swap from the last element all the way to the first element.
  14.         for (int index = lengthArray; index > 0; index--) {
  15.             // Picking a random index
  16.             int randomizedIndex = Stray.nextInt(index + 1);
  17.             // Swapping the element from Index to Randomized Index.
  18.             int temporaryElement = array[index];
  19.             array[index] = array[randomizedIndex];
  20.             array[randomizedIndex] = temporaryElement;
  21.         }
  22.         System.out.println(Arrays.toString(array));
  23.     }
  24.     // Main method
  25.     public static void main(String[] args) {
  26.         int[] array = {1, 4, 9, 16, 1, 25, 2, 6, 8, 10, 12, 3, 15, 18, 21, 24, 1, 4, 9, 4, 1};
  27.         int lengthArray = array.length;
  28.         System.out.println("Array before using The Fisher Yates Algorithm: " + Arrays.toString(array));
  29.         randomize(array, lengthArray);
  30.         System.out.println("Array after using The Fisher Yates Algorithm: " + Arrays.toString(array));
  31.     }
  32. }
  33.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement