Friday, 17 November 2017

Java Program to Implement Fisher-Yates Algorithm for Array Shuffling


Code:

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
            ind[i] = 0;
        int index;
        Random rand = new Random();
        for(int i=0; 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
        {
            a[i] = sc.nextInt();
        }
        res = fisherYatesShuffling(a, n);
        for(int i=0; i
        {
            System.out.print(res[i]+" ");
        }
        sc.close();
    }
}


Output:

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


More Java Programs:











100+ Best Home Decoration Ideas For Christmas Day 2019 To Make Home Beautiful

Best gifts for Christmas Day | Greeting cards for Christmas Day | Gift your children a new gift on Christmas day This Christmas d...