洗牌算法 数组打乱顺序 Fisher-Yates shuffle
来源:互联网 发布:java模拟http post请求 编辑:程序博客网 时间:2024/05/05 08:33
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;}
证明概率相等:
- 洗牌算法 数组打乱顺序 Fisher-Yates shuffle
- 洗牌算法Fisher–Yates shuffle
- 洗牌算法Fisher–Yates shuffle
- Fisher Yates 洗牌算法
- Fisher–Yates洗牌算法
- Fisher–Yates shuffle 算法
- Fisher–Yates Shuffle
- Fisher–Yates shuffle 算法——对给定数组进行乱序
- Fisher–Yates shuffle算法Go语言实现
- Fisher–Yates shuffle 算法 Go 语言实现
- Fisher–Yates shuffle 算法 Go 语言实现
- Fisher-Yates算法
- 洗牌算法:随机打乱一个数组的顺序
- 洗牌算法:随机打乱一个数组的顺序
- 洗牌算法:随机打乱一个数组的顺序
- 洗牌、发牌算法 (打乱扑克牌顺序)
- 洗牌、发牌算法 (打乱扑克牌顺序)
- 洗牌算法:随机打乱一个数组
- Mac OS中隐藏和显示文件的操作
- 坐标系变换经验
- Objective-C 中 @property (nonatomic,copy)声明里 nonatomic的作用
- Hibernate返回id比Oracle实际小1的问题
- MySql的CMake选项支持gcov和gprof
- 洗牌算法 数组打乱顺序 Fisher-Yates shuffle
- perl正则表达式
- Oracle/PLSQL: Replace Function
- 28个Unix/Linux的命令行神器
- javascript循环添加事件,总是获取最后一个值
- Perl目录操作
- OpenCv2.4在vs2010下配置过程
- perl文件操作
- ANT 编译警告: 编码 UTF-8 的不可映射字符解决方法