Fisher-Yates shuffle java example

Simple java implementation of “Fisher-Yates shuffle” algorithm with modification from Richard Durstenfeld. Also, this algorithm was popularized by Donald Knuth as “Algorithm P (Shuffling)” or “Knuth shuffle”.


Java implementation

public static <T> void shuffle(T[] array) {
    Random random = new Random();
    int n = array.length;
    for (int i = n - 1; i >= 1; i--) {
        int j = random.nextInt(i + 1);
        swap(array, i, j);
    }
}

private static <T> void swap(T[] array, int i, int j) {
    T temp = array[i];
    array[i] = array[j];
    array[j] = temp;
}

Usage

To demonstrate work of the code, let’s write helper method and its usage:

private static void shuffleAndPrint(Integer... array) {
    shuffle(array);
    System.out.println(Arrays.toString(array));
}

public static void main(String[] args) {
    shuffleAndPrint(1);          // => [1]
    shuffleAndPrint(1, 2);       // => [2, 1]
    shuffleAndPrint(1, 2, 3);    // => [3, 1, 2]
    shuffleAndPrint(1, 2, 3, 4); // => [2, 4, 3, 1]
}

Complete example

import java.util.Arrays;
import java.util.Random;

/**
 * @author Denis Migol
 */
public class FisherYatesShuffleExample {
    public static <T> void shuffle(T[] array) {
        Random random = new Random();
        int n = array.length;
        for (int i = n - 1; i >= 1; i--) {
            int j = random.nextInt(i + 1);
            swap(array, i, j);
        }
    }

    private static <T> void swap(T[] array, int i, int j) {
        T temp = array[i];
        array[i] = array[j];
        array[j] = temp;
    }

    public static void main(String[] args) {
        shuffleAndPrint(1);          // => [1]
        shuffleAndPrint(1, 2);       // => [2, 1]
        shuffleAndPrint(1, 2, 3);    // => [3, 1, 2]
        shuffleAndPrint(1, 2, 3, 4); // => [2, 4, 3, 1]
    }

    private static void shuffleAndPrint(Integer... array) {
        shuffle(array);
        System.out.println(Arrays.toString(array));
    }
}