Java Array Shuffle shuffle(final T[] array)

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

Description

shuffle

License

Open Source License

Declaration

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

Method Source Code

//package com.java2s;
/*/*from  w w  w  . j a v  a  2s .  c  o m*/
 * Hivemall: Hive scalable Machine Learning Library
 *
 * Copyright (C) 2013
 *   National Institute of Advanced Industrial Science and Technology (AIST)
 *   Registration Number: H25PRO-1520
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with this library; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA
 */

import java.util.Random;

public class Main {
    public static <T> void shuffle(final T[] array) {
        shuffle(array, array.length);
    }

    public static <T> void shuffle(final T[] array, final Random rnd) {
        shuffle(array, array.length, rnd);
    }

    public static <T> void shuffle(final T[] array, final int size) {
        Random rnd = new Random();
        shuffle(array, size, rnd);
    }

    public static <T> void shuffle(final T[] array, final int size, final Random rnd) {
        for (int i = size; i > 1; i--) {
            int randomPosition = rnd.nextInt(i);
            swap(array, i - 1, randomPosition);
        }
    }

    public static void swap(final Object[] arr, final int i, final int j) {
        Object tmp = arr[i];
        arr[i] = arr[j];
        arr[j] = tmp;
    }
}

Related

  1. shuffle(final A source, final Random random)
  2. shuffle(final Object[] array)
  3. shuffle(final Object[] values)
  4. shuffle(final T[] arr)
  5. shuffle(final T[] array)
  6. shuffle(int a[])
  7. shuffle(int arr[])
  8. shuffle(int size, boolean reallyShuffle)
  9. shuffle(int[] a)