Java Array Shuffle Shuffle(int[] v)

Here you can find the source of Shuffle(int[] v)

Description

Shuffle an array.

License

Open Source License

Parameter

Parameter Description
v Array.

Declaration

public static void Shuffle(int[] v) 

Method Source Code

//package com.java2s;
//    it under the terms of the GNU General Public License as published by

import java.util.Random;

public class Main {
    /**//w w w . j  a v  a 2 s  .  c om
     * Shuffle an array.
     * @param v Array.
     */
    public static void Shuffle(int[] v) {
        Shuffle(v, v.length);
    }

    /**
     * Shuffle an array.
     * @param v Array.
     */
    public static void Shuffle(int[] v, int times) {
        int n = Math.max(1, Math.min(v.length, times));
        Random random = new Random();
        random.nextInt();
        for (int i = 0; i < n; i++) {
            int change = i + random.nextInt(v.length - i);
            swap(v, i, change);
        }
    }

    private static void swap(int[] v, int i, int change) {
        int helper = v[i];
        v[i] = v[change];
        v[change] = helper;
    }
}

Related

  1. shuffle(int[] array, Random rand)
  2. shuffle(int[] array, Random rnd)
  3. shuffle(int[] ary)
  4. shuffle(int[] input)
  5. shuffle(int[] list, Random rnd)
  6. shuffle(Integer[] data)
  7. shuffle(List list)
  8. shuffle(List list)
  9. shuffle(List list, Random rnd)