Shuffle the elements of array in java

Java program for Shuffle the elements of array. Here problem description and other solutions.

/*
  Java program for
  Shuffle the array elements
*/
public class Shuffling
{
    // Function which is swapping two array elements 
    // of given location
    public static void swapElement(int[] arr, int i, int j)
    {
        // Get i location element
        int temp = arr[i];
        // Set new values
        arr[i] = arr[j];
        arr[j] = temp;
    }
    // Returns the random location of array elements
    public static int randomLocation(int min, int max)
    {
        // Calculate random number between given range
        return min + (int)(Math.random() * ((max - min) + 1));
    }
    // Function which is shuffle given array elements
    public static void shuffleElement(int[] arr, int size)
    {
        // (i,j) indicate locations
        int j = 0;
        int i = 0;
        // Variable which is controlling the 
        // execution process of loop
        int counter = 0;
        // Loop which is shuffling random elements in array
        while (counter < size)
        {
            // Get random location of array index
            i = randomLocation(0, size - 1);
            j = randomLocation(0, size - 1);
            if (i != j)
            {
                // Swap array elements
                swapElement(arr, i, j);
                counter++;
            }
        }
      
    }
    // Function which is display array elements
    public static void display(int[] arr, int size)
    {
        for (int i = 0; i < size; ++i)
        {
            // Disply element value
            System.out.print("  " + arr[i] );
        }
        System.out.print("\n");
    }
    public static void main(String[] args)
    {
  
        // Define array of integer elements
        int[] arr = {
            1 , 0 , -3 , 8 , 7 , 3 , 9 , 4 , 2 , 5 , 10 , 6
        };
        int size = arr.length;
        // Before shuffling  array elements
        System.out.println(" Initial array elements");
        display(arr, size);
        System.out.println(" After Shuffle array elements");
        shuffleElement(arr, size);
        display(arr, size);
        shuffleElement(arr, size);
        display(arr, size);
        shuffleElement(arr, size);
        display(arr, size);
    }
}

Output

 Initial array elements
  1  0  -3  8  7  3  9  4  2  5  10  6
 After Shuffle array elements
  2  8  0  4  7  3  6  10  9  5  1  -3
  3  10  6  7  4  2  1  9  0  8  5  -3
  2  7  6  5  -3  0  10  9  3  4  8  1

The result can be different result because it is based on random shuffling. Let's look at an example in the image below.

Shuffle the array elements


Please share your knowledge to improve code and content standard. Also submit your doubts, and test case. We improve by your feedback. We will try to resolve your query as soon as possible.

New Comment







© 2021, kalkicode.com, All rights reserved