首页 > 代码库 > [Python] Heap Sort in Python
[Python] Heap Sort in Python
代码:
#! /usr/bin/env python#coding=utf-8import random,copydef heap_sort_helper(lst,left,right): # max heapify current_value =http://www.mamicode.com/ lst[left] child = 2 * left + 1 while (child <= right): if (child < right and lst[child] < lst[child+1]): child = child + 1 if (current_value > lst[child]): break else: lst[(child-1)>>1] = lst[child] child = 2 * child + 1 lst[(child-1)>>1] = current_value def heap_sort(lst): # build heap for i in range((len(lst)-1)>>1,-1,-1): heap_sort_helper(lst,i,len(lst)-1) for i in range(len(lst)-1,0,-1): lst[i],lst[0] = lst[0],lst[i] heap_sort_helper(lst,0,i-1)if __name__ == "__main__": lst = [random.randint(0,20) for i in range(10)] lst2 = copy.deepcopy(lst) lst2.sort() print(lst) print(lst2) heap_sort(lst) print(lst)
测试数据:
[18, 3, 1, 20, 7, 5, 4, 10, 16, 6]
[1, 3, 4, 5, 6, 7, 10, 16, 18, 20]
[1, 3, 4, 5, 6, 7, 10, 16, 18, 20]
[Python] Heap Sort in Python
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。