void permute(int a[], int n){
for (int i = n; i > 0; --i){
swap(a[i-1], a[rand()%i]);
}
// a[i-1] 与 a[0, i)(包括 a[i-1]) 中某一随机元素交换
}
这也是 JDK 源码 Collections.shuffle 的实现原理:
public static void shuffle(List<?> list, Random rnd) {
int size = list.size();
if (size < SHUFFLE_THRESHOLD || list instanceof RandomAccess) {
for (int i=size; i>1; i--)
swap(list, i-1, rnd.nextInt(i));
} else {
Object arr[] = list.toArray();
// Shuffle array
for (int i=size; i>1; i--)
swap(arr, i-1, rnd.nextInt(i));
ListIterator it = list.listIterator();
for (int i=0; i<arr.length; i++) {
it.next();
it.set(arr[i]);
}
}
}