How to Shuffle an Array in Java
The Challenge
Randomly shuffle (randomize) the elements of an array!
Solutions
Method 1: Using Collections.shuffle()
import java.util.*;
Integer[] numbers = {1, 2, 3, 4, 5};
List<Integer> list = Arrays.asList(numbers);
Collections.shuffle(list);
System.out.println(Arrays.toString(numbers));
// Output: [3, 1, 5, 2, 4] (random order)Method 2: Fisher-Yates Shuffle (Manual)
import java.util.Random;
int[] numbers = {1, 2, 3, 4, 5};
Random rand = new Random();
for (int i = numbers.length - 1; i > 0; i--) {
int j = rand.nextInt(i + 1);
// Swap numbers[i] and numbers[j]
int temp = numbers[i];
numbers[i] = numbers[j];
numbers[j] = temp;
}
System.out.println(Arrays.toString(numbers));
// Output: [4, 1, 3, 5, 2] (random order)Did You Know?
The Fisher-Yates shuffle algorithm guarantees that every permutation is equally likely - it's the gold standard for shuffling!
Pro Tip
Use Collections.shuffle() for simplicity, or implement Fisher-Yates for primitive arrays or custom shuffling logic!
Real-World Use Cases
- Card games: Shuffle deck of cards
- Quizzes: Randomize question order
- Playlists: Shuffle music tracks
- Testing: Randomize test data
›Short versionOpen if you only have a minute.
- Fisher-Yates swaps index i with a random index in the not-yet-fixed range.
- Picking a random index from the whole array on every step biases the permutation.
- Collections.shuffle does Fisher-Yates for a List.
- One Random instance, created outside the loop. A seed makes a test repeatable.
Shuffle an array
Reorder elements so that each permutation is equally likely.
Working approach
- Walk i from the last index down to 1.
- Draw j uniformly from 0 through i inclusive.
- Swap i and j.
Walk the sample
- Length 4
- At i = 3, swap with an index in 0..3
- At i = 2, swap with an index in 0..2
- Stop after i = 1
The trap
Swapping with a fresh index in 0..n-1 at every position feels random and is not uniform. Some orders come up more often than others.
static void shuffle(int[] values, Random random) {
for (int i = values.length - 1; i > 0; i--) {
int j = random.nextInt(i + 1);
int held = values[i];
values[i] = values[j];
values[j] = held;
}
}Why is a swap against a random index in the whole array biased?
An element can be moved again after it has already been placed, and the early positions are not equally likely to hold each value.
Fisher-Yates never touches an index above i again. Each permutation has the same probability, 1/n!. Collections.shuffle is that algorithm for a list. The shuffle also mutates the array you pass in.
Time O(n), extra space O(1).
Easy to get wrong
- Drawing the swap index from the full range on every iteration.
- Constructing a new Random inside the loop.