This is java implementation of the Fisher–Yates shuffle (named after Ronald Fisher and Frank Yates)algorithm, also known as the Knuth shuffle (after Donald Knuth), for generating a random permutation of a finite set—in plain terms, for randomly shuffling the set.
Here is the source code of the Java Program to Implement Fisher-Yates Algorithm for Array Shuffling. The Java program is successfully compiled and run on a Windows system. The program output is also shown below.
//This is a sample program to shuffle the elements of an array using Fisher Yates Array Shuffling algorithm
import java.util.Random;
import java.util.Scanner;
public class Fisher_Yates_Array_Shuffling
{
static int[] fisherYatesShuffling(int []arr, int n)
{
int []a = new int[n];
int []ind = new int[n];
for(int i=0; i<n; i++)
ind[i] = 0;
int index;
Random rand = new Random();
for(int i=0; i<n; i++)
{
do
{
index = rand.nextInt(n);
} while(ind[index] != 0);
ind[index] = 1;
a[i] = arr[index];
}
return a;
}
public static void main(String agrs[])
{
Scanner sc = new Scanner(System.in);
System.out.println("Enter the array size: ");
int n = sc.nextInt();
System.out.println("Enter the array elements: ");
int []a = new int[n];
int []res = new int[n];
for(int i=0; i<n; i++)
{
a[i] = sc.nextInt();
}
res = fisherYatesShuffling(a, n);
for(int i=0; i<n; i++)
{
System.out.print(res[i]+" ");
}
sc.close();
}
}
Output:
$ javac Fisher_Yates_Array_Shuffling.java $ java Fisher_Yates_Array_Shuffling Enter the array size: 12 Enter the array elements: 1 2 3 4 5 6 7 8 9 10 11 12 The shuffled elements are: 7 10 8 4 9 6 12 3 2 1 5 11
Related posts:
Guide to the Java TransferQueue
Guide to Guava Table
Custom Thread Pools In Java 8 Parallel Streams
Working with Kotlin and JPA
Java Program to Check Whether a Directed Graph Contains a Eulerian Path
REST Web service: HTTP Status Code và xử lý ngoại lệ RESTful web service với Jersey 2.x
Static Content in Spring WebFlux
Apache Tiles Integration with Spring MVC
Java Program to Implement Sieve Of Sundaram
Java Program to Implement the Binary Counting Method to Generate Subsets of a Set
Introduction to Spring MVC HandlerInterceptor
Java – Create a File
Spring MVC Content Negotiation
Redirect to Different Pages after Login with Spring Security
List Interface trong Java
Deploy a Spring Boot App to Azure
Hướng dẫn Java Design Pattern – Memento
Java Map With Case-Insensitive Keys
Java Program to Check the Connectivity of Graph Using DFS
Introduction to Java 8 Streams
Spring Boot - Interceptor
Collect a Java Stream to an Immutable Collection
Java Program to Perform Complex Number Multiplication
Java Program to Implement Splay Tree
A Guide to WatchService in Java NIO2
Java Program to Find Transpose of a Graph Matrix
Java Program to Implement HashTable API
ExecutorService – Waiting for Threads to Finish
Database Migrations with Flyway
Java – File to Reader
Java – Random Long, Float, Integer and Double
The Thread.join() Method in Java