通过划分的方式在线性时间内找出一个序列中第K大的元素

这种划分在快速排序中也用到了:

#py2.7
#coding:utf-8
import random

def findkth(ll, k):
    if k > len(ll):
        raise Exception('Argument error')
    else:
        pivot = ll[random.randrange(0,len(ll))]
        last = 0
        for i in range(1, len(ll)):
            if ll[i] >= pivot:
                last += 1
                swap(ll, i, last)
        swap(ll, 0, last)
        print(ll,k)
        order = last+1
        if order == k:
            return pivot
        elif order < k:
            return findkth(ll[last + 1:], k - order)
        else:
            return findkth(ll[0:last], k)


def swap(ll, i, last):
    tmp = ll[i]
    ll[i] = ll[last]
    ll[last] = tmp


ll = [1, 22, 31, 14, 0.5, 26, 17, 38, 19, 310]
k = 3
print(findkth(ll, k))


posted @ 2013-10-26 19:44  爱知菜  阅读(185)  评论(0编辑  收藏  举报