sortCommon.pyhtml
#!/usr/bin/python def swap(dataArray, i, j): temp = dataArray[i] dataArray[i] = dataArray[j] dataArray[j] = temp
heap.pypython
from sortCommon import swap class Heap(object): def __init__(self): self.queue = [] #上浮 def shiftUp(self, i): while(int(i/2)>=0): if self.queue[i] < self.queue[int(i/2)]: swap(self.queue, i, int(i/2)) i = int(i/2) else:break #下沉 def shiftDown(self, i): size = len(self.queue) while(int(i*2+1)<size): t = int(i*2+1) if t+1 < size and self.queue[t+1] < self.queue[t]: t+=1 if self.queue[i] > self.queue[t]: swap(self.queue, i, t) i = t else:break def push(self, x): self.queue.append(x) self.shiftUp(len(self.queue)-1) print(self.queue) def pop(self): swap(self.queue,0,len(self.queue)-1) del self.queue[len(self.queue)-1] self.shiftDown(0) print(self.queue) def top(self): return self.queue[0] def empty(self): return len(self.queue) == 0 if __name__ == '__main__': heap = Heap() size = int(input('請輸入堆的節點數:')) for i in range(size): num = int(input('請輸入一個數字:')) heap.push(num) print('從上到下輸出堆頂元素') for i in range(size): print(heap.top()) heap.pop()
參考連接:數組
http://www.javashuo.com/article/p-wjfxplqz-z.htmlapp
不過這個連接中的下沉方法中彷佛有些錯誤,由於它的例子是實現小端堆,因此應該是把大的數字往下沉,因此在Shift_downy方法中的code
if( 堆數組名[ i ] < 堆數組名[ T ] )
應該改成htm
if( 堆數組名[ i ] > 堆數組名[ T ] )