Java Program to Shuffle a Given Array of Integers

bookmark

import java.util.*;
import java.util.Scanner;
public class Main
{
    public static void main(String args[])
    {
        // Creating the array
        int arr[] = {12, 2, 34, 20, 54, 6, 52, 8, 9, 68};
        // Prints the array elements
        System.out.println("The array elements are "+Arrays.toString(arr));
        
        shuffle(arr);
        // Prints the array elements
        System.out.println("The array elements after shuffling "+Arrays.toString(arr));
    }
    
    // Funbction that shuffles the array elements
    static void shuffle(int arr[])
    {
        Random rand = new Random();
        int randomVariable, temp;
        for(int i=arr.length-1; i>=1;i-- )
        {
            // Finds a random number between 0 and the current location of array
            randomVariable= rand.nextInt(i+1);
            // Swaps the elements
            temp = arr[i];
            arr[i] = arr[randomVariable];
            arr[randomVariable] = temp;
        }
    }
}
 

 

Output:

The array elements are [12, 2, 34, 20, 54, 6, 52, 8, 9, 68]
The array elements after shuffling [20, 8, 2, 9, 68, 34, 54, 6, 12, 52]