Java Array Shuffle shuffle(T[] array)

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

Description

Shuffles the given array.

License

Apache License

Return

mutated parameter array that was shuffled beforehand.

Declaration

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

Method Source Code

//package com.java2s;
//License from project: Apache License 

import java.util.Random;

public class Main {
    /**/*from w  w  w  .  j a va2s . c  om*/
     * Shuffles the given array.
     * 
     * @return mutated parameter array that was shuffled beforehand.
     */
    public static <T> T[] shuffle(T[] array) {
        return shuffle(array, new Random());
    }

    /**
     * Shuffles the given array with the given random function.
     * 
     * @return mutated parameter array that was shuffled beforehand.
     */
    public static <T> T[] shuffle(T[] array, Random rnd) {
        for (int i = array.length; i > 1; i--)
            swap(array, i - 1, rnd.nextInt(i));
        return array;
    }

    /**
     * Swaps the given indices x with y in the array.
     */
    public static void swap(int[] array, int x, int y) {
        int tmpIndex = array[x];
        array[x] = array[y];
        array[y] = tmpIndex;
    }

    /**
     * Swaps the given indices x with y in the array.
     */
    public static void swap(long[] array, int x, int y) {
        long tmpIndex = array[x];
        array[x] = array[y];
        array[y] = tmpIndex;
    }

    /**
     * Swaps the given indices x with y in the array.
     */
    public static void swap(double[] array, int x, int y) {
        double tmpIndex = array[x];
        array[x] = array[y];
        array[y] = tmpIndex;
    }

    /**
     * Swaps the given indices x with y in the array.
     */
    public static void swap(boolean[] array, int x, int y) {
        boolean tmpIndex = array[x];
        array[x] = array[y];
        array[y] = tmpIndex;
    }

    /**
     * Swaps the given indices x with y in the array.
     */
    public static <T> void swap(T[] array, int x, int y) {
        T tmpIndex = array[x];
        array[x] = array[y];
        array[y] = tmpIndex;
    }
}

Related

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