C-Sharp | Java | Python | Swift | GO | WPF | Ruby | Scala | F# | JavaScript | SQL | PHP | Angular | HTML
Swap: Then we swap the randomly selected "forward" element with the current element.
Result: The input array (in this code, an int array) is now randomly sorted. Like a deck of cards, it is shuffled.
NextInt: It is important to use nextInt instead a multiplication with Math.Random to avoid bias in the results.
Java program that implements Fisher-Yates shuffle
public class Program {
static void shuffle(int[] array) {
int n = array.length;
Random random = new Random();
// Loop over array.
for (int i = 0; i < array.length; i++) {
// Get a random index of the array past the current index.
// ... The argument is an exclusive bound.
// It will not go past the array's end.
int randomValue = i + random.nextInt(n - i);
// Swap the random element with the present element.
int randomElement = array[randomValue];
array[randomValue] = array[i];
array[i] = randomElement;
}
}
public static void main(String[] args) {
int[] values = { 100, 200, 10, 20, 30, 1, 2, 3 };
// Shuffle integer array.
shuffle(values);
// Display elements in array.
for (int value : values) {
System.out.println(value);
}
}
}
Output
10
100
1
200
3
20
2
30
Here: We call Collections.shuffle multiple times on an ArrayList. Its ordering changes after each call.
Java program that uses Collections.shuffle
import java.util.ArrayList;
import java.util.Collections;
public class Program {
public static void main(String[] args) {
// Create an ArrayList of 4 elements.
ArrayList<Integer> array = new ArrayList<>();
array.add(1);
array.add(2);
array.add(3);
array.add(4);
System.out.println("BEFORE: " + array.toString());
// Shuffle elements.
Collections.shuffle(array);
System.out.println("AFTER 1: " + array.toString());
// Shuffle elements again.
Collections.shuffle(array);
System.out.println("AFTER 2: " + array.toString());
}
}
Output
BEFORE: [1, 2, 3, 4]
AFTER 1: [3, 2, 4, 1]
AFTER 2: [4, 1, 3, 2]
Quote: Fisher-Yates shuffling is similar to randomly picking numbered tickets out of a hat without replacement until there are none left.
Fisher-Yates shuffle: WikipediaCorrection: Thanks to Alan Evans for correcting a bias caused by Math.Random. It is better to use nextInt for the shuffle.
And: This will randomly sort (or shuffle) the array, provided our random number generator is random enough.
However: This is not fast. But if your program only shuffles occasionally, this may be fast enough.