Wednesday, August 27, 2025
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

Dominic
32236 POSTS0 COMMENTS
Milvus
80 POSTS0 COMMENTS
Nango Kala
6609 POSTS0 COMMENTS
Nicole Veronica
11779 POSTS0 COMMENTS
Nokonwaba Nkukhwana
11828 POSTS0 COMMENTS
Shaida Kate Naidoo
6719 POSTS0 COMMENTS
Ted Musemwa
7002 POSTS0 COMMENTS
Thapelo Manthata
6678 POSTS0 COMMENTS
Umr Jansen
6690 POSTS0 COMMENTS