OneBite.Dev - Coding blog in a bite size

shuffle the elements in an array in java

Code snippet on how to shuffle the elements in an array in java

  public static void shuffleArray(int[] ar)
  {
    // If running on Java 6 or older, use `new Random()` on RHS here
    Random rnd = ThreadLocalRandom.current();
    for (int i = ar.length - 1; i > 0; i--)
    {
      int index = rnd.nextInt(i + 1);
      // Simple swap
      int a = ar[index];
      ar[index] = ar[i];
      ar[i] = a;
    }
  }

This code shuffles the elements in an array. It starts by defining a function ‘shuffleArray’ that takes an array as an argument. It then uses Java’s Random class and its ‘nextInt’ method to generate a random index. It then swaps the element at that index with the element at the end of the array. It repeats this loop until it reaches the beginning of the array, effectively shuffling the elements. This is an efficient way to randomly rearrange elements in an array.

java