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








  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值