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