码迷,mamicode.com
首页 > 编程语言 > 详细

[Python] Heap Sort in Python

时间:2015-01-17 22:07:01      阅读:318      评论:0      收藏:0      [点我收藏+]

标签:

 代码:

#! /usr/bin/env python
#coding=utf-8

import random,copy

def heap_sort_helper(lst,left,right):
    # max heapify
    current_value = 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

标签:

原文地址:http://www.cnblogs.com/kimberly/p/4231088.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!