Java Array Shuffle shuffle(int[] array)

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

Description

Fisher-Yates implementation which shuffles the array contents.

License

Open Source License

Parameter

Parameter Description
array the array of ints to shuffle.

Return

shuffled array

Declaration

public static int[] shuffle(int[] array) 

Method Source Code

//package com.java2s;
/* ---------------------------------------------------------------------
 * Numenta Platform for Intelligent Computing (NuPIC)
 * Copyright (C) 2014, Numenta, Inc.  Unless you have an agreement
 * with Numenta, Inc., for a separate license for this software code, the
 * following terms and conditions apply:
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Affero Public License version 3 as
 * published by the Free Software Foundation.
 *
 * This program 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 Affero Public License for more details.
 *
 * You should have received a copy of the GNU Affero Public License
 * along with this program.  If not, see http://www.gnu.org/licenses.
 *
 * http://numenta.org/licenses//* w ww. j  a  v a 2s  . co  m*/
 * ---------------------------------------------------------------------
 */

import java.util.Random;

public class Main {
    /**
     * Fisher-Yates implementation which shuffles the array contents.
     * 
     * @param array     the array of ints to shuffle.
     * @return shuffled array
     */
    public static int[] shuffle(int[] array) {
        int index;
        Random random = new Random(42);
        for (int i = array.length - 1; i > 0; i--) {
            index = random.nextInt(i + 1);
            if (index != i) {
                array[index] ^= array[i];
                array[i] ^= array[index];
                array[index] ^= array[i];
            }
        }
        return array;
    }
}

Related

  1. shuffle(int arr[])
  2. shuffle(int size, boolean reallyShuffle)
  3. shuffle(int[] a)
  4. shuffle(int[] arr)
  5. shuffle(int[] arr)
  6. shuffle(int[] array)
  7. shuffle(int[] array)
  8. shuffle(int[] array)
  9. shuffle(int[] array)