Python 类快速排序方法找到第定n小数的方法,python小数,python 用类快排的


python 用类快排的方法找寻"第n小"的数,Python 类快速排序方法找到第定n小数的方法。

(n)快速排序风格基于排序算法查找数据。
有用的寻找中位数,百分位数、四分位数和十分位数。
相当于数据[n]当已经排序的数据。

#coding=utf-8import randomdef select(data, n):    "Find the nth rank ordered element (the least value has rank 0)."    data = list(data)    if not 0 <= n < len(data):        raise ValueError('not enough elements for the given rank')    while True:        pivot = random.choice(data)        pcount = 0        under, over = [], []        uappend, oappend = under.append, over.append#www.iplaypy.com    for elem in data:       if elem < pivot:    uappend(elem)       elif elem > pivot:    oappend(elem)     else:       pcount += 1       if n < len(under):         data = under      elif n < len(under) + pcount:         return pivot       else:       data = over n -= len(under) + pcount

编橙之家文章,

评论关闭