python---的topk算法

#! conding:utf-8

author = “hotpot”
date = “2017/10/26 9:42”

def quick_index(array, start, end):
    left, right = start, end
    key = array[left]
    while left < right:
        while left < right and array[right] > key:
            right -= 1
        array[left] = array[right]
        while left < right and array[left] < key:
            left += 1
        array[right] = array[left]

    array[left] = key
    return left


def min_num(array, m):
    start, end = 0, len(array) - 1
    index = quick_index(array, start, end)
    while index != m:
        if index < m:
            index = quick_index(array, index+1, end)
        else:
            index = quick_index(array, start, index)

    print(array[:m])

if __name__ == '__main__':
    alist = [15,54, 26, 93, 17, 77, 31, 44, 55, 20]

    min_num(alist,  5)

你可能感兴趣的:(python)