Shuffle array elements in Java

Hey there, code champs! In this tutorial, you are going to learn a Java program to shuffle elements in an array. We are going to achieve this by using the Random class in Java.

Random class: RandomĀ class in Java is used to generate random numbers. To use the random class, we need to create a Random object like below:

Random rand = new Random();

This will create a Random object. This object gives you access to methods likeĀ nextInt() (a method used to generate random integer numbers) and nextDouble() (a method used to generate random decimal numbers). This random class is majorly applicable to introduce unpredictability into your code.

Java program to shuffle array elements

Consider the following example.

An example array with 5 elements present in it.

For the above example, the loop will start at the end of the array and go backward to the first element. For each element at index i, a random index j is generated due to the random class. The random index j is always in the range [0, i]. After obtaining the indexes i and j we need to swap the elements at these indexes. This process repeats itself in a loop until it reaches the first element.

Because we are using the random class the outputs generated are always changing.

import java.util.*;  
public class Codespeedy{  
    public static void main(String[] args) {
        System.out.println("Enter the size of the array: ");
        Scanner sc= new Scanner(System.in);
        int N=sc.nextInt();
        int[] array = new int[N];
        System.out.println("Enter the elements: ");
        for(int i=0;i<=N-1;i++){
            array[i]=sc.nextInt();
        }
        shuffleArray(array);
        System.out.println("After shuffling: ");
        for (int i=0;i<=N-1;i++) {
            System.out.print(array[i]+" ");
        }
    }
    public static void shuffleArray(int[] array) {
        Random rand = new Random();
        for (int i = array.length - 1; i > 0; i--) {
            int j = rand.nextInt(i + 1);
            int temp = array[i];
            array[i] = array[j];
            array[j] = temp;
        }
    }
}
Output:
Enter the size of the array: 
5
Enter the elements: 
1
2
3
4
5
After shuffling: 
4 2 3 1 5

Hope this tutorial was helpful!

Leave a Reply

Your email address will not be published. Required fields are marked *