Java Array Shuffle shuffle(T[] array)

Here you can find the source of shuffle(T[] array)

Description

Rearranges the array items in random order using the default java.util.Random generator.

License

Open Source License

Parameter

Parameter Description
array a parameter

Declaration

public static <T> void shuffle(T[] array) 

Method Source Code

//package com.java2s;

import java.util.Random;

public class Main {
    /**//from www  . jav a2  s .c  o  m
     * Rearranges the array items in random order using the default
     * java.util.Random generator. Operation is in-place, no copy is created.
     * 
     * @param array
     */
    public static <T> void shuffle(T[] array) {
        shuffle(array, new Random());
    }

    /**
     * Rearranges the array items in random order using the given RNG. Operation
     * is in-place, no copy is created.
     * 
     * @param array
     * @param rnd
     */
    public static <T> void shuffle(T[] array, Random rnd) {
        int N = array.length;
        for (int i = 0; i < N; i++) {
            int r = i + rnd.nextInt(N - i); // between i and N-1
            T swap = array[i];
            array[i] = array[r];
            array[r] = swap;
        }
    }
}

Related

  1. shuffle(Random rand, O[] array)
  2. shuffle(short... a)
  3. shuffle(String str, Random randObj)
  4. shuffle(T[] a, int from, int to, Random rnd)
  5. shuffle(T[] array)
  6. shuffle(T[] array)
  7. shuffle(T[] array, Random rand)
  8. shuffle(T[] array, Random rand)
  9. shuffle(T[] array, Random random)