Algorithm ——数组打乱算法
Fisher–Yates shuffle 算法是一个非常高效又公平的随机排序算法(打乱有序的算法),它的时间复杂度为O(n)。它的实现伪代码大致是:
n = A.length;
for i = 1 to n
swap A[i] with A[RANDOM(i, n)]
在进行第i次迭代时,元素A[i]时从元素A[i]到A[n]中随机选取的。第i次迭代后,A[i]不再改变。
Fisher–Yates shuffle算法的Java实现即测试代码如下所示:
public class RandomAlgor {
static int[] A = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15 };
public static void main(String[] args) {
fisherYatesShuffle(A);
System.out.println("打乱后的数组");
arrayPrint(A);
}
/**
* 数组随机排序:洗牌算法(Fisher–Yates shuffle 费雪-耶兹洗牌算法)
*
* @param A
*/
public static void fisherYatesShuffle(int[] A) {
int rand = 0;
int swap = 0;
int n = A.length;
Random util = new Random();
for (int i = n - 1; i > 0; i--) {
rand = Math.abs(util.nextInt() % (i + 1));// 随机生成一个待置换的数组下标,它的范围是[0,i]
if (rand != i) {
swap = A[i];
A[i] = A[rand];
A[rand] = swap;
}
}
}
public static void arrayPrint(int[] array) {
System.out.print("[");
for (int i = 0; i < array.length; i++) {
System.out.print(array[i] + ", ");
}
System.out.println("]");
}
}