Java Array Shuffle shuffle(byte[] array)

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

Description

Randomly shuffle elements within an array.

License

Open Source License

Parameter

Parameter Description
array a parameter

Declaration

public static void shuffle(byte[] array) 

Method Source Code

//package com.java2s;
/*/*  www.  j  a va  2s.co  m*/
 * Copyright (C) 2014 Raul Gracia-Tinedo
 * 
 * This program is free software: you can redistribute it and/or modify it under 
 * the terms of the GNU General Public License as published by the Free Software 
 * Foundation, either version 3 of the License, or (at your option) any later 
 * version.
 * 
 * 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 General Public License for more details.
 * 
 * You should have received a copy of the GNU General Public License along with 
 * this program. If not, see http://www.gnu.org/licenses/.
 */

import java.util.Random;

public class Main {
    /**
     * Randomly shuffle elements within an array.
     * 
     * @param array
     */
    public static void shuffle(byte[] array) {
        shuffle(new Random(), array);
    }

    /**
     * Randomly shuffle elements within an array.
     * 
     * @param array
     */
    public static void shuffle(Random random, byte[] array) {
        int count = array.length;
        for (int i = count; i > 1; i--) {
            swap(array, i - 1, random.nextInt(i));
        }
    }

    private static void swap(byte[] array, int i, int j) {
        byte temp = array[i];
        array[i] = array[j];
        array[j] = temp;
    }
}

Related

  1. randomize(final T[] array)
  2. shuffle()
  3. shuffle(byte[] values, Random rnd)
  4. shuffle(Collection items, Random random)
  5. shuffle(Collection objects)
  6. shuffle(double[] arr, Random rnd)