从n个数中找出最小(or最大)的k个数

#算法时间复杂度:,最坏:k=2/n,O(n^2);最好:k=1或者n-1,O(n)
# 本算法不用排序

def n_k(list_input,k):
    for i in range(k,len(list_input)):
        max = float("-inf")
        for j in range(k):
            if  max < list_input[j]:
                max = list_input[j]
                index_max = j
                print(j)
        if list_input[i] < max:
            (list_input[index_max],list_input[i]) = (list_input[i],list_input[index_max])
    return list_input[0:k]

# test
a=[11,4,9,3,7,5,2,8,19,38,-1,100,-100]
n_k(a,5)

本方法不用排序操作,得到的结果也是无序的。

猜你喜欢

转载自www.cnblogs.com/Lewis_Liu/p/select_top_k_from_n.html