Monday, November 18, 2024
Google search engine
HomeLanguagesJavaJava Program To Jumble an Array

Java Program To Jumble an Array

Given an array of size N, and the task is to shuffle the elements of the array or any other permutation. Using Java think of stuffing the array by generating random sequences of the elements present in the array is possible. This Algorithm is called Fisher-Yates Shuffle Algorithm.

Fisher–Yates shuffle Algorithm Works in O(n) time complexity. The assumption is that a give a function rand() generates a random number in O(1) time. Start from the last element, swap it with a randomly selected element from the whole array. Now consider the array from 0 to n-2 (size reduced by 1), and repeat till we hit the first element.

Example:

Input : arr[] = {1, 2, 3, 4}
Output: arr[] = {3, 2, 4, 1}

Input : arr[] = {5, 2, 3, 4}
Output: arr[] = {2, 4, 3, 5}

Algorithm:

  for i from n - 1 downto 1 do
       j = random integer with 0 <= j <= i
       exchange a[j] and a[i]

Below is the implementation of the above approach:

Java




// Program to jumble an array  using Java
import java.util.Random;
import java.io.*;
  
public class GFG {
    public static void shuffleanarray(int[] a)
    {
        int n = a.length;
        Random random = new Random();
        // generating random number from list
        random.nextInt();
        
        for (int i = 0; i < n; i++) {
            
            // using random generated number
            int change = i + random.nextInt(n - i);
            
            // swapping elements to shuffle
            int holder = a[i];
            a[i] = a[change];
            a[change] = holder;
        }
    }
    public static void main(String[] args)
    {
        int[] a = new int[] { 0, 1, 2, 3, 4, 5, 6 };
        shuffleanarray(a);
        System.out.print("arr[] = {");
        for (int i : a) {
            System.out.print(i + " ");
        }
        System.out.print("}");
    }
}


Output

arr[] = {4 0 6 1 5 3 2 }

Time Complexity: O(N), where N is the size of an array.

RELATED ARTICLES

Most Popular

Recent Comments