基于堆排序的topk

import random

def generate_big_root_heap(li,low,hight):
    i = low
    j = 2 * i + 1
    tmp = li[i]
    while j <= hight:
        if j + 1 <= hight and li[j+1] > li[j]:
            j = j + 1
        if li[j] > tmp:
            li[i] = li[j]
            i = j
            j = 2 * i + 1
        else:
            break
    li[i] = tmp

def generate_low_root_heap(li,low,hight):
    i = low
    j = 2 * i + 1
    tmp = li[low]
    while j <= hight:
        if j + 1 <= hight and li[j+1] < li[j]:
            j = j + 1
        if li[j] < tmp:
            li[i] = li[j]
            i = j
            j = 2 * i + 1
        else:
            break
    li[i] = tmp

def topk(li,k):
    heap = li[:k]
    for i in range((k-1-1)//2,-1,-1):
        generate_low_root_heap(heap,i,k-1)
    for i in range(k,len(li)-1):
        if li[i] > heap[0]:
            heap[0] = li[i]
            generate_low_root_heap(heap,0,k-1)
    for i in range(k-1,-1,-1):
        heap[i], heap[0] = heap[0], heap[i]
        generate_low_root_heap(heap,0,i-1)
    return heap



def main():
    li = [i for i in range(100)]
    random.shuffle(li)
    print(li)
    heap = topk(li,10)
    print(heap)

if __name__ == '__main__':
    main()

  

posted @ 2021-11-20 13:38  NAVYSUMMER  阅读(59)  评论(0编辑  收藏  举报
交流群 编程书籍