zoukankan      html  css  js  c++  java
  • 基于堆排序的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()
    

      

  • 相关阅读:
    获取窗口句柄
    LeetCode Q136 Single Number(Medium)
    异或
    Ring3层的鼠标和键盘Hook
    Java—Applet
    Java—常用数据类型
    Java—接口与抽象类
    Java 概述
    Java—类的封装、继承与多态
    Windows—JDK安装与环境变量配置
  • 原文地址:https://www.cnblogs.com/navysummer/p/15580982.html
Copyright © 2011-2022 走看看