Here you can find the source of shuffleArray(T[] arr)
Parameter | Description |
---|---|
T | Array-type |
arr | Array to shuffle |
public static <T> void shuffleArray(T[] arr)
//package com.java2s; //License from project: Open Source License import java.util.Random; public class Main { /**/*from www. j av a 2 s .co m*/ * Random number generator. */ private static final java.util.Random rand = new Random(); /** * Permutes the elements of the given array. * * @param <T> * Array-type * @param arr * Array to shuffle */ public static <T> void shuffleArray(T[] arr) { for (int i = arr.length; i > 1; i--) swap(arr, i - 1, rand.nextInt(i)); } /** * Swaps the elements at position <code>a</code> and <code>b</code> in the * array <code>arr</code>. * * @param <T> * Type of array elements * @param arr * Array that contains the elements to be swapped * @param a * First position * @param b * Second position */ public static <T> void swap(T[] arr, int a, int b) { if (a < 0 || a > arr.length || b < 0 || b > arr.length) throw new IllegalArgumentException("swap position out of bounds."); if (a != b) { T t = arr[a]; arr[a] = arr[b]; arr[b] = t; } } }