洗牌算法 数组打乱顺序 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;}

证明概率相等: