Java Utililty Methods Array Shuffle

List of utility methods to do Array Shuffle

Description

The list of methods to do Array Shuffle are organized into topic(s).

Method

T[]shuffle(T[] array)
Shuffles the given array.
return shuffle(array, new Random());
T[]shuffle(T[] array)
shuffle
T[] nArr = array.clone();
List<Integer> keys = new ArrayList<>(array.length);
for (int i = 0; i < array.length; ++i)
    keys.add(i);
for (T obj : array) {
    int i = rand(0, keys.size());
    int index = keys.get(i);
    keys.remove(i);
...
voidshuffle(T[] array)
Rearranges the array items in random order using the default java.util.Random generator.
shuffle(array, new Random());
voidshuffle(T[] array, Random rand)
Randomly shuffle an array in place.
for (int i = 0; i < array.length; i++) {
    int index = rand.nextInt(array.length);
    T temp = array[index];
    array[index] = array[i];
    array[i] = temp;
voidshuffle(T[] array, Random rand)
shuffle
int i, j, size = array.length - 1;
for (i = 0; i < size; i++) {
    j = rand.nextInt(size - i) + i + 1;
    swap(array, i, j);
voidshuffle(T[] array, Random random)
shuffle
int count;
if (array != null && (count = array.length) > 1) {
    for (int index = count - 1; index > 0; --index) {
        int newIndex = random.nextInt(index + 1);
        T temp = array[index];
        array[index] = array[newIndex];
        array[newIndex] = temp;
voidshuffle(T[] data)
shuffle
int n = data.length;
int n1 = n - 0x01;
T tmp;
for (int i = 0x00; i < n1; i++) {
    tmp = data[i];
    int j = nextInt(n1 - i) + i;
    data[i] = data[j];
    data[j] = tmp;
...
voidshuffleArray(double[] ar)
Implementing Fisher-Yates shuffle
Random rnd = new Random();
for (int i = ar.length - 1; i >= 0; i--) {
    int index = rnd.nextInt(i + 1);
    double a = ar[index];
    ar[index] = ar[i];
    ar[i] = a;
int[]shuffleArray(int arr[])
shuffle Array
if (arr == null || arr.length == 0)
    return arr;
for (int i = arr.length - 1; i >= 1; i--) {
    int j = RANDOM.nextInt(i + 1);
    int tmp = arr[j];
    arr[j] = arr[i];
    arr[i] = tmp;
return arr;
voidshuffleArray(int[] a)
Shuffle an array for integers

EXAMPLE:
Array [1,2,3,4,5,6] getting shuffled
After shuffle [2,1,6,3,5,4] or any other combination

int n = a.length;
Random random = new Random();
random.nextInt();
for (int i = 0; i < n; i++) {
    int change = i + random.nextInt(n - i);
    swap(a, i, change);