In the previous article, we have seen Java Program to Find the Smallest Number in an Array
In this article we are going to see how we can shuffle an array of integers in Java.
Java Program to Shuffle a Given Array of Integers
Array is a data structure which stores a fixed size sequential collection of values of single type. Where with every array elements/values memory location is associated. Each array elements have it’s own index where array index starts from 0.
In Array set of variables referenced by a single variable name and it’s array index position. It is also called as a container object which contains elements of similar type.
Declaration of an array:
dataType[] arrayName; (or) //Declaring an array dataType []arrayName; (or) dataType arr[];
Instantiation of an Array:
arrayName = new datatype[size]; //Allocating memory to array
Combining both Statements in One:
dataType[] arrayName = new dataType[size] //Declaring and Instantiating array
Initialization of an Array:
arrayName[index-0]= arrayElement1 //Initializing the array ... arrayName[index-s]= arrayElementS
Combining all Statements in One:
dataType arrayName[ ]={e1,e2,e3}; //declaration, instantiation and initialization
Let’s see different ways to shuffle an array of integers.
Method-1: Java Program to Shuffle a Given Array of Integers By Using Fisher-Yates Algorithm
Approach:
- Create an array of integers with elements.
- Display the array to the user.
- Traverse through the array using a for loop
- Swap the element at each location with a random element present in the array.
- Display the array to the user.
Program:
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; } } }
Program: 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]
Are you wondering how to seek help from subject matter experts and learn the Java language? Go with these Basic Java Programming Examples and try to code all of them on your own then check with the exact code provided by expert programmers.
Related Java Programs: