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

algorithm: heap sort in python 算法导论 堆排序

时间:2015-02-25 22:19:46      阅读:185      评论:0      收藏:0      [点我收藏+]

标签:

An Python implementation of heap-sort

based on the detailed algorithm description in Introduction to Algorithms Third Edition
import random

def max_heapify(arr, i, length):
    while True:
        l, r = i * 2 + 1, i * 2 + 2
        largest = l if l < length and arr[l] > arr[i] else i
        if r < length and arr[r] > arr[largest]:
            largest = r
        if largest != i:
            arr[i], arr[largest], i = arr[largest], arr[i], largest
        else:
            break

def build_heap(arr):
    for i in range(len(arr) / 2, -1, -1):
        max_heapify(l, i, len(arr))

def heap_sort(arr):
    build_heap(arr)
    length = len(arr)
    for i in range(1, length):
        arr[0], arr[-i] = arr[-i], arr[0]
        max_heapify(arr, 0, length - i)

if __name__ == __main__:
    l = [random.randint(1, 113) for i in range(18)]
    print l
    heap_sort(l)
    print l

 

algorithm: heap sort in python 算法导论 堆排序

标签:

原文地址:http://www.cnblogs.com/ydlme/p/4300302.html

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