| Shuffle array in Java |
|
|
|
| Written by Charles | |||||
| Saturday, 05 December 2009 11:42 | |||||
|
The Java SDK gave us Collections.shuffle but not Arrays.shuffle. Here is a way of shuffling an array based on the algorithm of the former. The code is HERE
public class ArrayShuffle {
public static void main(String[] args) { // Create an array of int 1 - 7 Integer[] ints = { 1, 2, 3, 4, 5, 6, 7 }; // Shuffle it ArrayShuffle.shuffle(ints); // Print the result System.out.println(java.util.Arrays.toString(ints)); } /** * Shuffle an array of type T * * @param <T> The type contained in the array * @param array The array to be shuffled */ public static <T> void shuffle(T[] array) { for (int i = array.length; i > 1; i--) { T temp = array[i - 1]; int randIx = (int) (Math.random() * i); array[i - 1] = array[randIx]; array[randIx] = temp; } } }
Only registered users can write comments!
Powered by !JoomlaComment 3.26
3.26 Copyright (C) 2008 Compojoom.com / Copyright (C) 2007 Alain Georgette / Copyright (C) 2006 Frantisek Hliva. All rights reserved." |
|||||
| Last Updated ( Saturday, 05 December 2009 11:55 ) |



