Java Array Shuffle shuffle(int a[])

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

Description

Shuffles (randomizes) the contents of the given array.

License

Open Source License

Parameter

Parameter Description
a the array

Declaration

public static void shuffle(int a[]) 

Method Source Code


//package com.java2s;
//License from project: Open Source License 

import java.util.Random;

public class Main {
    /** A random number generator. */
    public static Random random = new Random(System.currentTimeMillis());

    /**/*from ww w .ja  va 2s. c o  m*/
     * Shuffles (randomizes) the contents of the given array.
     * 
     * @param a
     *            the array
     */
    public static void shuffle(int a[]) {
        for (int i = 0; i < a.length - 1; i++) {
            int tmp = a[i];
            int index = i + 1 + random.nextInt(a.length - i - 1);
            a[i] = a[index];
            a[index] = tmp;
        }
    }

    /**
     * Shuffles (randomizes) the contents of the given array.
     * 
     * @param a
     *            the array
     */
    public static void shuffle(Object a[]) {
        for (int i = 0; i < a.length - 1; i++) {
            Object tmp = a[i];
            int index = i + 1 + random.nextInt(a.length - i - 1);
            a[i] = a[index];
            a[index] = tmp;
        }
    }
}

Related

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