Shuffle an Array or a List in Java

How can we rearrange an array of items in random order? A simple way is to manipulate the array by picking elements randomly. Or we can use Java Collections API.

Shuffle an Array

Write a loop to go through each position, and assign it with a randomly chosen element. This method runs in linear time.

public static void shuffle(int[] a)
{
    int n = a.length;
    for (int i = 0; i < n; i++)
    {
        // between i and n-1
        int r = i + (int) (Math.random() * (n-i));
        int tmp = a[i];    // swap
        a[i] = a[r];
        a[r] = tmp;
    }
}

...
int[] a = { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9};
shuffle(a);
System.out.println(Arrays.toString(a));

Use java.util.Collection.shuffle()

Java Collections API provides a static method in the Collection class for shuffling.

public static void shuffle(List<?> list)

Similarly as the approach above, this implementation traverses the list backwards, from the last element up to the second, repeatedly swapping a randomly selected element into the “current position”. Elements are randomly selected from the portion of the list that runs from the first element to the current position, inclusive.

To use it, we need to have a List object.

Integer[] a = new Integer[] { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9};
// int[] does not work
Collections.shuffle(Arrays.asList(a));

The method Arrays.asList() returns a fixed-size list backed by the specified array.

Comments

comments

Tagged with: , ,
Posted in Java