Selection in expected linear time O(n)

来源:互联网 发布:rrt路径规划算法 编辑:程序博客网 时间:2024/06/06 04:04


Selection in expected linear time



           The general selection problem appears more difficult than the simple problem of finding a minimum. Yet, surprisingly, the asymptotic running time for both problems is the same: theta(n).

          In this section, we present a divide-and-conquer algorithm for the selection problem. The algorithm R ANDOMIZED-SELECT is modeled after the quicksort algorithm of Chapter 7. As in quicksort, we partition the input array recursively. But unlike quicksort, which recursively processes both sides of the partition, R ANDOMIZED -S ELECT works on only one side of the partition. This difference shows up in the analysis: whereas quicksort has an expected running time of theta{n*lg(n)}, the expected running time of RANDOMIZED-S ELECT is O(n), assuming that the elements are distinct.


下面是random_select()的实现:

返回在输入数据中,第i大的数据,时间复杂度是O(n)

"""Code writer : EOFCode date   : 2015.01.15Code file   : random_select.pye-mail      : jasonleaster@gmail.comCode description :      Here is a implementation for random-select in Python.Function  @random_select(A, p, r, i) will return the i-thelement from the @A which's range is @p to @r."""import randomdef partition(A, p, r) :    x = A[r]    i = p-1    for j in range(p, r) :        if A[j] <= x :           i += 1           # swap A[i] and A[j]           A[i], A[j] = A[j], A[i]     A[i+1], A[r] = A[r], A[i+1]    return i+1def random_partition(A, p, r) :    i = random.randint(p,r)    A[r], A[i] = A[i], A[r]    return partition(A, p, r)def random_select(A, p, r, i) :    if p == r :       return A[p]    q = random_partition(A, p ,r)    k = q - p + 1    if i == k :       return A[q]    elif i < k :       return random_select(A, p, q-1, i)    else :       return random_select(A, q+1, r, i-k)#-------------------testing code---------------------------A = [13,19,9,5,12,8,7,4,21,2,6,11]print "Before sorting A= " , Ax = random_select(A,0,len(A)-1, 5)print "After  sorting A= " , sorted(A), x












0 0
原创粉丝点击
热门问题 老师的惩罚 人脸识别 我在镇武司摸鱼那些年 重生之率土为王 我在大康的咸鱼生活 盘龙之生命进化 天生仙种 凡人之先天五行 春回大明朝 姑娘不必设防,我是瞎子 手机桌面文件夹打不开怎么办 苹果下载不了150怎么办 iphone6速度变慢怎么办 苹果手机微信打不开pdf怎么办 苹果手机打不开pdf怎么办 pdf文件超过了怎么办 pdf电脑删不了怎么办 联想笔记本摄像头横屏调竖屏怎么办 pdf文件打开失败怎么办 pdf复制文字乱码怎么办 电子发票乱码了怎么办 超星尔雅挂了怎么办 电脑应用双击打不开怎么办 电脑控制面板打不开怎么办 转换器无法打开文件怎么办 电脑文件无法打开怎么办 手机上jpg打不开怎么办 脸上全是黄褐斑怎么办 容易发胖的体质怎么办 感冒后一直咳嗽怎么办 感冒咳嗽怎么办小窍门 到了减肥平台期怎么办 减肥遇见平台期怎么办 脚冻伤了痒怎么办 冬天脚后跟冻了怎么办 夏天脚冻了怎么办 导航软件删了怎么办 婆婆爱打孩子怎么办 乙肝婆婆带孩子怎么办 婆婆不会教孩子怎么办 婆婆不会带孩子怎么办 公婆枪带孩子怎么办 婆婆要带孩子怎么办 婆婆太惯孩子怎么办 三个月宝宝溢奶怎么办 孩子半夜咳嗽吐怎么办 中老年人转氨酶和血指高怎么办 孩子逆反心强怎么办 孩子学习逆反了怎么办 翼支付登陆不了怎么办 微波炉鸡蛋炸了怎么办