用Python实现大顶堆

#!/usr/bin/env python2
# -*- coding: utf-8 -*-
"""
Created on Wed May 10 18:52:57 2017

@author: zz
"""

class MaxHeap:
    def __init__(self, data):
        data.insert(0, None)
        self.heap = data
        self.heapSize = 0
        for i in range(1,len(self.heap)):
            self.heapSize += 1
            self.__bubble(i)

    def __sink(self, pos):
        left, right = 2*pos, 2*pos+1
        next = pos
        if left <= self.heapSize and self.compare(self.heap[left], self.heap[next]) > 0:
            next = left
        if right <= self.heapSize and self.compare(self.heap[right], self.heap[next]) > 0:
            next = right
        if next == pos:
            return
        self.__exchange(pos, next)
        return self.__sink(next)

    def __bubble(self, pos): # build
        if pos <= 1:
            return
        ppos = pos/2
        if self.compare(self.heap[pos], self.heap[ppos]) > 0:
            self.__exchange(pos, ppos)
            return self.__bubble(ppos)

    def compare(self, a, b):
        return a - b

    def __exchange(self, i, j):
        temp = self.heap[i]
        self.heap[i] = self.heap[j]
        self.heap[j] = temp

    def sort(self):
        while self.heapSize > 1:
            self.__exchange(1, self.heapSize)
            self.heapSize -= 1
            self.__sink(1)
        self.heap.remove(None)
        return self.heap


maxHeap = MaxHeap([4, 5, 7, 7, 1, 3, 8, -1])
print maxHeap.sort()

运行结果

[-1, 1, 3, 4, 5, 7, 7, 8]

你可能感兴趣的:(算法)