Java Array Shuffle shuffle(int[] array)

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

Description

Shuffle the values of an int array into random order

License

Apache License

Parameter

Parameter Description
array The array to shuffle

Declaration

public static void shuffle(int[] array) 

Method Source Code

//package com.java2s;
/**//from  w  w w .  ja v  a 2  s .  c om
 * ArrayUtils.java
 *
 * Subject to the apache license v. 2.0
 *
 * http://www.apache.org/licenses/LICENSE-2.0.txt
 *
 * @author william@rattat.com
 */

import java.util.Random;

public class Main {
    /**
     * Random instance used to shuffle arrays
     */
    private static Random random = null;

    /**
     * Shuffle the values of an int array into random order
     *
     * @param array The array to shuffle
     */
    public static void shuffle(int[] array) {
        if (array == null) {
            return;
        }

        for (int i = 0; i < array.length; i++) {
            int r = i + random.nextInt(array.length - i);

            int tmp = array[i];
            array[i] = array[r];
            array[r] = tmp;
        }
    }

    /**
     * Shuffle the values of an object array into random order
     *
     * @param array The array to shuffle
     */
    public static void shuffle(Object[] array) {
        if (array == null) {
            return;
        }

        for (int i = 0; i < array.length; i++) {
            int r = i + random.nextInt(array.length - i);

            Object tmp = array[i];
            array[i] = array[r];
            array[r] = tmp;
        }
    }

    /**
     * Shuffle the values of a double array into random order
     *
     * @param array The array to shuffle
     */
    public static void shuffle(double[] array) {
        if (array == null) {
            return;
        }

        for (int i = 0; i < array.length; i++) {
            int r = i + random.nextInt(array.length - i);

            double tmp = array[i];
            array[i] = array[r];
            array[r] = tmp;
        }
    }
}

Related

  1. shuffle(int[] arr)
  2. shuffle(int[] array)
  3. shuffle(int[] array)
  4. shuffle(int[] array)
  5. shuffle(int[] array)
  6. shuffle(int[] array, Random rand)
  7. shuffle(int[] array, Random rand)
  8. shuffle(int[] array, Random rnd)
  9. shuffle(int[] ary)