Java Array Shuffle shuffleArray(T[] arr)

Here you can find the source of shuffleArray(T[] arr)

Description

Permutes the elements of the given array.

License

Open Source License

Parameter

Parameter Description
T Array-type
arr Array to shuffle

Declaration

public static <T> void shuffleArray(T[] arr) 

Method Source Code

//package com.java2s;
//License from project: Open Source License 

import java.util.Random;

public class Main {
    /**/*from   www. j av  a 2  s .co m*/
     * Random number generator.
     */
    private static final java.util.Random rand = new Random();

    /**
     * Permutes the elements of the given array.
     * 
     * @param <T>
     *            Array-type
     * @param arr
     *            Array to shuffle
     */
    public static <T> void shuffleArray(T[] arr) {
        for (int i = arr.length; i > 1; i--)
            swap(arr, i - 1, rand.nextInt(i));
    }

    /**
     * Swaps the elements at position <code>a</code> and <code>b</code> in the
     * array <code>arr</code>.
     * 
     * @param <T>
     *            Type of array elements
     * @param arr
     *            Array that contains the elements to be swapped
     * @param a
     *            First position
     * @param b
     *            Second position
     */
    public static <T> void swap(T[] arr, int a, int b) {
        if (a < 0 || a > arr.length || b < 0 || b > arr.length)
            throw new IllegalArgumentException("swap position out of bounds.");
        if (a != b) {
            T t = arr[a];
            arr[a] = arr[b];
            arr[b] = t;
        }
    }
}

Related

  1. shuffleArray(int[] array, int length)
  2. shuffleArray(int[] array, long rngSeed)
  3. shuffleArray(List list)
  4. shuffleArray(Object[] array)
  5. shuffleArray(T[] ar)
  6. shuffled(List list, Random random)
  7. shuffledList(List list)
  8. shuffleInPlace(E[] elems, Random rand)
  9. shuffleInPlace(int[] toShuffle, Random random)