python实现堆排序

#!/usr/bin/env python
# -*- coding: utf-8 -*-

def heap_sort(arr):
    l = len(arr)
    for i in xrange(l/2, -1, -1):
        form_heap(arr, i, l-1)
    for i in xrange(l-1, 0, -1):
        arr[i],arr[0] = arr[0],arr[i]
        form_heap(arr, 0, i-1)
    return

def form_heap(arr, start, end):
    while(start < end):
        tmp = start * 2
        if tmp > end:
            break
        if tmp +1 <= end and  arr[tmp + 1] > arr[tmp]:
            tmp = tmp + 1
        if arr[tmp] > arr[start]:
            arr[tmp],arr[start] = arr[start], arr[tmp]
        start = tmp

heap_sort(arr)
#form_heap(arr, 3,len(arr) -1)
print arr

  

posted @ 2017-10-18 15:40  天空中的蜂蜂  阅读(157)  评论(0编辑  收藏  举报