找出最小或者最大的几个数我使用的是堆排序,效率为0(nlgn)
构建小顶堆返回末尾的k个数 或者 构建大顶堆返回前k个数
1 #!/usr/bin/env python3 2 3 def heap_sort(ary, num): 4 def siftdown(ary, e, begin, end): 5 i,j = begin, begin*2+1 6 while j < end: 7 if j+1 < end and ary[j+1] < ary[j]: 8 j += 1 9 if e < ary[j]: 10 break 11 ary[i] = ary[j] 12 i,j = j,j*2+1 13 ary[i] = e 14 15 end = len(ary) 16 for i in range(end//2-1, -1, -1): 17 siftdown(ary, ary[i], i, end) 18 19 #方法1 20 for i in range(end-1, -1, -1): 21 e = ary[i] 22 ary[i] = ary[0] 23 siftdown(ary, e, 0, i) 24 return ary[:-num-1:-1] 25 26 #方法2 27 """ 28 li = [] 29 for i in range(num): 30 if len(ary) > i: 31 li.append(ary[0]) 32 e = ary[end-1-i] 33 siftdown(ary, e, 0, end-1-i) 34 else: 35 break 36 return li 37 """ 38 39 if __name__ == '__main__': 40 a = [4,5,1,6,2,7,3,8] 41 num = int(input("最小的k个数:")) 42 print(heap_sort(a,num))