RosettaCodeData/Task/Knuth_shuffle/Java/knuth_shuffle.java
Ingy döt Net 1e05ecd7ee First commit of partial RosettaCode contents.
Pushing this for testing purposes. Lots of work still needed.
2013-04-08 13:02:41 -07:00

24 lines
642 B
Java

import java.util.Random;
public static final Random gen = new Random();
// version for array of ints
public static void shuffle (int[] array) {
int n = array.length;
while (n > 1) {
int k = gen.nextInt(n--); //decrements after using the value
int temp = array[n];
array[n] = array[k];
array[k] = temp;
}
}
// version for array of references
public static void shuffle (Object[] array) {
int n = array.length;
while (n > 1) {
int k = gen.nextInt(n--); //decrements after using the value
Object temp = array[n];
array[n] = array[k];
array[k] = temp;
}
}