Fisher-Yates shuffle of an array - Java java.lang

Java examples for java.lang:Math Array Function

Description

Fisher-Yates shuffle of an array

Demo Code


//package com.java2s;

import java.util.Random;

public class Main {
    /**/* w  w  w.  ja v a2  s  . c o m*/
     * Fisher-Yates shuffle of an array
     * @param ar 
     */
    public static void shuffleArray(int[] ar) {
        Random rnd = new Random();
        for (int i = ar.length - 1; i >= 0; i--) {
            int index = rnd.nextInt(i + 1);
            // Simple swap
            int a = ar[index];
            ar[index] = ar[i];
            ar[i] = a;
        }
    }
}

Related Tutorials