最坏情况为线性时间的选择算法之Python实现
来源:互联网 发布:魔方社区网络覆盖 编辑:程序博客网 时间:2024/04/29 23:01
算法导论第三版,9.3
import randomimport math#returns the number of elements that smaller than x#the input is A[p...r] inclusive in the convention of book, 1 <= p <= r <= n#in Python, to represent A[p...r], we should use a[p-1:r] def partition(a,p,r,x): low = [m for m in a if m < x] high = [m for m in a if m > x] a[p-1:r] = low + [x] + high return len(low)def median(a): a.sort() return a[(len(a)+1)/2 - 1]#x is the ith smallest element means there are (i-1) elements smaller than x#x is the 1st smallest means x is the smallestdef select(a,i): if len(a) == 1: return a[0] #1.divide into n/5 groups groups = [] numOfGroups = int(math.ceil(len(a)*1.0/5)) start,end = 0,0 for j in range(0,numOfGroups-1): start = j*5 end = start + 5 groups.append(a[start:end]) groups.append(a[end:]) #2.find the median of each group medians = [] for g in groups: medians.append(median(g)) #3.find the median of the n/5 medians x = select(medians,(len(medians)+1)/2) #4.partition the array with x,so x is the kth smallest element k = partition(a,1,len(a),x) + 1 #5. if k == i : return x #if k is greager than i,means there are too many elements smaller than x, #we need to narrow the range elif k > i : #SELECT (A[1...k],i) return select(a[0:k],i) #if k is not enough,we need to find the result from the other side else: #SELECT (A[k+1...n],i - k) return select(a[k:],i-k)#test selectresult = []for i in range(10000): a = random.sample(range(100), 21) order = random.randint(1,20) r1 = select(a,order) a.sort() r2 = a[order-1] result.append(r1==r2)print(all(result))
0 0
- 最坏情况为线性时间的选择算法之Python实现
- 最坏情况为线性时间的选择算法
- CLRS 9.3最坏情况为线性时间的选择算法
- (p123)最坏情况为线性时间的选择算法
- 最坏情况为线性时间的选择算法
- 算法导论-第九章-中位数和顺序统计量:最坏情况为线性时间的选择算法C++实现
- 第九章中位数和顺序统计学 之 “寻找第i小元素之最坏情况线性时间的选择 最坏运行时间就为O(n)算法”
- 算法导论第9章最坏情况为线性时间的选择算法
- 算法导论 最坏情况为线性时间的选择算法 9.3-8 9.3-9
- 最坏情况为线性时间的选择算法---算法导论学习笔记(2)
- 最坏情况下为O(N)的线性时间选择
- 最坏情况下的线性时间的选择算法
- 最坏情况线性时间的选择 java实现
- (基于Java)算法之最坏情况下的线性时间选择
- 算法之分治——最坏情况线性时间的选择
- 算法导论:第9章 中位数和顺序统计量_2最坏情况为线性时间的选择算法
- 《算法导论》读书笔记之第9章 中位数和顺序统计学 最坏情况是线性时间的选择算法
- 最坏线性时间的python实现 。
- sizeof运算符(注:不是函数)
- HDU1241 Oil Deposits
- GZIP压缩原理分析(04)——第三章 gzip文件格式详解(三02) gzip文件头
- 探索String、StringBuilder、StringBuffer
- centos7下安装编译并搭建hadoop2.6.0单节点伪分布式集群
- 最坏情况为线性时间的选择算法之Python实现
- Oculus Rift 没有声音的解决方法
- 写给小白的ECMAScript 6学习教程
- Twitter发布新的大数据实时分析系统Heron
- 怎么卸载oracle
- Light OJ 1275 Internet Service Providers (数学)
- NYOJ-27水池数目
- Android中级:事件传递机制
- 运动估计和运动补偿