How to Shuffle, Shuffle, Shuffle an Array in Java

Question:

In other languages ​​there are functions to randomly mix the elements of an array (such as the shuffle function in PHP), in the case of Java I do not know if there is any similar function, so at the moment I see that functions created from code for that purpose.

On many pages ( like the official site in English ) codes for functions are provided that can solve the problem, but some of the solutions found seem to be somewhat out of date.

Even many times the answers that circulate on the internet are not entirely effective and do not work 100% of the cases.

What is sought is that the algorithm can:

  • Disorder arrays that contain any type of elements (characters, numbers, strings, arrays, etc.).
  • That can mess up arrays of any size.
  • and that the result has an acceptable degree of entropy (disorder).

Here a code example in java

private static void shuffleArray(int[] array)
{
    int index;
    Random random = new Random();
    for (int i = array.length - 1; i > 0; i--)
    {
        index = random.nextInt(i + 1);
        if (index != i)
        {
            array[index] ^= array[i];
            array[i] ^= array[index];
            array[index] ^= array[i];
        }
    }
}

Code obtained from Random shuffling of an array

How can I unorder any type of array regardless of the size and type of elements it contains with a shorter code with fewer lines?

Thank you.

Answer:

To start with, let's tackle the problem of a shuffling algorithm. An algorithm that you can use that works "in-place" and has O (N) complexity is Knut's algorithm that you can consult here . This is the step by step of the algorithm:

  1. For each site i from 0 to N :
    • Select a random number j between 0 and N
    • Swap the values ​​at sites i and j
  2. Ready 🙂

Then, as for your question of how to shuffle any type of data, you should familiarize yourself with the subject of generics in Java .

An implementation that you can use that meets both requirements goes as follows:

package shuffle;

import java.util.Random;

public class App {
    public static void main(String[] args) {
        Integer[] numbers = { 1, 3, 4, 5 };
        shuffle(numbers);
        for (int number: numbers) {
            System.out.println(number);
        }
    }

    /**
     * Swap two items of an array.
     * ...
     */
    protected static <T> void swap(T[] array, int i, int j) {
        T temp = array[i];
        array[i] = array[j];
        array[j] = temp;
    }

    /**
     * Shuffle an arbitrary array with Knut's algorithm.
     * ...
     */
    public static <T> void shuffle(T[] array) {
        Random random = new Random();
        int i = 0;
        for (int j : random.ints(array.length, 0, array.length).toArray()) {
            swap(array, i++, j);
        }
    }

}

The swap function swap the numbers in the array, while the shuffle function shuffle through the elements and generates the random numbers.

The <T> parameters allow these functions to support any type of object, to use them you add <T> before the return type and then you use the type T in arguments or in the body of the function. However, it should be noted that generics do not work with primitive types like int or char , so the arrays must be of types like Integer , String , etc.

Scroll to Top