Last active
October 22, 2018 10:59
-
-
Save diaolizhi/9a74fbe53a18a39aabf217af2758013f to your computer and use it in GitHub Desktop.
Java 数组随机打乱顺序
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public static void shuffle(Object[] a) { | |
//判断数组 a 是否可以转为整型数组 | |
validateNotNull(a); | |
int n = a.length; | |
for (int i = 0; i < n; i++) { | |
int r = i + uniform(n-i); // between i and n-1 | |
Object temp = a[i]; | |
a[i] = a[r]; | |
a[r] = temp; | |
} | |
} | |
public static int uniform(int n) { | |
if (n <= 0) throw new IllegalArgumentException("argument must be positive: " + n); | |
return random.nextInt(n); | |
} | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment