The Fisher-Yates algorithm is a method for generating a random permutation of a finite sequence. Here is how you can integrate the Fisher-Yates shuffle algorithm in the existing Java class:
import java.util.Random;
public class ArrayAlgorithms {
// ... [Other methods are not repeated for brevity. Include them from the previous example.]
public static void fisherYatesShuffle(int[] array) {
Random random = new Random();
for (int i = array.length - 1; i > 0; i--) {
int index = random.nextInt(i + 1);
int temp = array[index];
array[index] = array[i];
array[i] = temp;
}
}
public static void main(String[] args) {
// ... [Other operations are not repeated for brevity. Include them from the previous example.]
int[] arrayToShuffle = {12, 7, 5, 3, 11, 8, 4};
System.out.println("Array before Fisher-Yates Shuffle:");
printArray(arrayToShuffle);
fisherYatesShuffle(arrayToShuffle);
System.out.println("Array after Fisher-Yates Shuffle:");
printArray(arrayToShuffle);
}
}
Here is how the Fisher-Yates algorithm works:
- Start with the last element of the array.
- Generate a random index between 0 and the index of the last element (inclusive).
- Swap the elements at the generated index and the last element.
- Move to the previous element and repeat the process until the entire array is shuffled.
This algorithm produces a uniformly random permutation of the input array, assuming that the used random number generator has good uniform distribution.