惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

Apple Machine Learning Research
Apple Machine Learning Research
Y
Y Combinator Blog
博客园 - 【当耐特】
V
Visual Studio Blog
GbyAI
GbyAI
V
V2EX
P
Proofpoint News Feed
Microsoft Azure Blog
Microsoft Azure Blog
Microsoft Security Blog
Microsoft Security Blog
D
DataBreaches.Net
Hugging Face - Blog
Hugging Face - Blog
A
About on SuperTechFans
The Cloudflare Blog
阮一峰的网络日志
阮一峰的网络日志
Cyber Security Advisories - MS-ISAC
Cyber Security Advisories - MS-ISAC
N
Netflix TechBlog - Medium
aimingoo的专栏
aimingoo的专栏
B
Blog RSS Feed
量子位
MongoDB | Blog
MongoDB | Blog
有赞技术团队
有赞技术团队
人人都是产品经理
人人都是产品经理
Stack Overflow Blog
Stack Overflow Blog
小众软件
小众软件

博客园 - dragonpig

Html 5 Canvas绘制分形图Mandelbrot .net中反射、emit、expression和dynamic的性能比较 const string 和 static readonly string的区别 SqlServer: Top N per Group 微软的BinarySearch 通过CTE实现Split CSV 通过SQL CTE计算Fibonacci 当json.js遇见dynamic.net烂尾篇 .NET线程安全泛型Singleton 跨域访问Cookie WCF JSON和AspnetCompatibility的配置 Windows安装Memcached node.js初体验 教你如何制作Silverlight Visual Tree Inspector 一道非常有趣的概率题 教你30秒打造强类型ASP.NET数据绑定 当json.js遇见dynamic.net [0] 用Silverlight做雷达图 C#运算符重载不是没有用武之地
随机排列算法
dragonpig · 2011-01-16 · via 博客园 - dragonpig

随机排列是个很常用的算法,比如洗牌。算法思想很简单,比如有一副整理好的牌,每次随机抽取一张最后就组成一副随机的牌了,并且可以证明所有可能性的排列是等概率的。但是该算法的空间复杂度是O(n),如果每次抽牌都插入到头部,则最坏情况下的时间复杂度是O(n*n)。参考Introduction to Algorithm 5.3的算法,其实对第二种方法稍作改进就可以达到O(n)。算法如下:

  1. 保持头部的以抽取队列,以及尾部的为抽取队列,一开始头为空,尾为满。
  2. 从尾部随机抽牌,与尾部第一张交换,头部加一,尾部减一
  3. 直到尾部为空

以下是javascript代码

var array = [1,2,3,4];
for(var i=0,len=array.length;i<len-1;i++){
var pos = i + Math.floor((len - i)*Math.random());
var tmp = array[pos];
array[pos]
= array[i];
array[i]
= tmp;
}
alert(array.join(
', '));