堆排序

#__author__=lx
#__date__=2011-09-29
#__brief__=Heap_sort


def left( i ):
        return 2*i

def right( i ):
        return 2*i + 1

def swap( a1, a2 ):
        return a2, a1

def max_heap( A, i ):

        if i == 0:
                return

        l = left( i )
        r = right( i )
        largest = i

        if l < len( A ):
                if A[ l ] > A[ i ] :
                        largest = l
                else:
                        largest = i

        if r < len( A ):
                if A[ r ] > A[ largest ]:
                        largest = r

        if largest != i:
                A[i], A[largest] = swap( A[i], A[largest] )
                max_heap( A, largest )

        return A


def build_max_heap( A ):
        i = len( A ) / 2

        while ( i >= 1 ):
                max_heap( A, i )
                i -= 1


def heap_sort( A ):
        build_max_heap( A )

        i = len( A ) - 1

        while ( i >= 2 ):
                A[1], A[i] = swap( A[1], A[i] )
                print A[-1]
                A = max_heap( A[ :-1 ], 1 )
                i -= 1

        print A[-1]

if __name__ == "__main__":
        d = [ 0, 4, 1, 3, 2, 16, 9, 10, 14, 8, 7 ]

        heap_sort( d )
                                                  

  

posted @ 2011-09-29 18:51  lxgeek  阅读(132)  评论(0编辑  收藏  举报