Skip to content

Instantly share code, notes, and snippets.

@tonetheman
Created May 29, 2010 01:36
Show Gist options
  • Save tonetheman/417948 to your computer and use it in GitHub Desktop.
Save tonetheman/417948 to your computer and use it in GitHub Desktop.
import java.util.Random;
public class Shuffler {
public static Random r = new Random();
public static void swap(int[] a, int i, int s) {
int tmp = a[i];
int tmp2 = a[s];
a[i] = tmp2;
a[s] = tmp;
}
public static void print(int[] a) {
if(a==null) return;
for(int i=0;i<a.length;i++) {
System.out.print(a[i] + " ");
}
System.out.println();
}
public static void fisher_yates_shuffle(int [] a) {
if (a.length>1) {
int i = a.length - 1;
while (i>0) {
int s = r.nextInt(i+1);
swap(a,i,s);
i--;
}
}
}
public static void main(String[] args) {
int [] a = {1,2,3,4,5};
fisher_yates_shuffle(a);
print(a);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment