洗牌算法 数组打乱顺序 Fisher-Yates shuffle

http://en.wikipedia.org/wiki/Fisher%E2%80%93Yates_shuffle

大公司面试题见过几次 今天实现以下 其实MODERN算法很简单


1. 实现的是in-place算法,以后有空把其他的完成

2. 每次启动程序种子需要变化,以当前时间为种子

#include <iostream>
#include <time.h>

void swap(int* a, int* b)
{
	int tmp = *a;
	*a = *b;
	*b = tmp;
};


void random_shuffling(int *a, int n)
{
	int i = n - 1;
	int j;
	while(i > 0)
	{
		j = rand() % (i + 1);
		swap(&a[i], &a[j]);
		i--;
	}
};


int main()
{
	srand(time(0));
	int a[10] = {1,2,3,4,5,6,7,8,9,10};
	random_shuffling(a, 10);

	for(int i = 0; i < 10; i++)
	{
		std::cout << a[i] << " ";
	}

	return 0;
}

增补:下面这个是一边初始化 一边shuffle算法 大同小异

#include <iostream>
#include <time.h>

const int N = 10;

void swap(int* a, int* b)
{
	int tmp = *a;
	*a = *b;
	*b = tmp;
};


void random_shuffling(int *source)
{
	int* res = new int[N];

	res[0] = source[0];

	int i = 1;
	int j;

	while(i < N)
	{
		j = rand() % (i + 1);
		res[i] = source[i];
		swap(&res[i], &res[j]);

		i++;
	}

	for(int i = 0; i < N; i++)
	{
		std::cout << res[i] << " ";
	}
};


int main()
{
	srand(time(0));
	int source[10] = {1,2,3,4,5,6,7,8,9,10};
	random_shuffling(source);



	return 0;
}

证明概率相等:


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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值