简单洗牌算法

来源:互联网 发布:爱养成血族女王数据 编辑:程序博客网 时间:2024/06/05 15:35

一个简单高效的洗牌算法,C代码。

#include <stdio.h>#include <stdlib.h>#include <time.h>/* * 每次随机抽取一张牌放入数组后部 */void shuffle(short *poker, short len) {int i;srand((unsigned)time(NULL));for ( i=len-1; i>=1; i-- ) {int k = rand()%(i);int x = poker[k];poker[k] = poker[i];poker[i] = x;}}int main(void) {short LEN = 54, i;short *poker = malloc(LEN);for ( i=0; i<LEN; i++ )poker[i] = i;shuffle(poker, LEN);for ( i=0; i<LEN; i++ )printf("%d ", poker[i]);free(poker);return EXIT_SUCCESS;}


原创粉丝点击