Java Array Shuffle shuffleArray(int[] a)

Here you can find the source of shuffleArray(int[] a)

Description

Shuffle an array for integers

EXAMPLE:
Array [1,2,3,4,5,6] getting shuffled
After shuffle [2,1,6,3,5,4] or any other combination

License

Apache License

Parameter

Parameter Description
a array to shuffle

Declaration

public static void shuffleArray(int[] a) 

Method Source Code

//package com.java2s;
/*******************************************************************************
 * Copyright 2012-Present, MoribitoTech/*  www.  j a v  a 2s  .co  m*/
 * 
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * 
 *   http://www.apache.org/licenses/LICENSE-2.0
 * 
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 ******************************************************************************/

import java.util.Random;

public class Main {
    /**
     * Shuffle an array for integers
     * <p>
     * EXAMPLE: <br>
     * Array [1,2,3,4,5,6] getting shuffled <br>
     * After shuffle [2,1,6,3,5,4] or any other combination
     * 
     * @param a
     *            array to shuffle
     * */
    public static void shuffleArray(int[] a) {
        int n = a.length;
        Random random = new Random();
        random.nextInt();
        for (int i = 0; i < n; i++) {
            int change = i + random.nextInt(n - i);
            swap(a, i, change);
        }
    }

    /**
     * Shuffle helper
     * */
    public static void swap(int[] a, int i, int change) {
        int helper = a[i];
        a[i] = a[change];
        a[change] = helper;
    }
}

Related

  1. shuffle(T[] array, Random rand)
  2. shuffle(T[] array, Random random)
  3. shuffle(T[] data)
  4. shuffleArray(double[] ar)
  5. shuffleArray(int arr[])
  6. shuffleArray(int[] ar)
  7. shuffleArray(int[] ar)
  8. shuffleArray(int[] ar, Random rnd, int mx)
  9. shuffleArray(int[] arr)