1. 程式人生 > >Algorithm ——陣列打亂演算法(七)

Algorithm ——陣列打亂演算法(七)

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("]");
	}
}