大頂堆是一種結合二叉樹的排序演算法,平均時間複雜度為ο(nlogn) ,不清楚該演算法的可以先看詳細的介紹
# -*- coding: utf-8 -*-
class heaptree(object):
leftchild = none
rightchild = none
value = none
# 排好順序的節點設定不可訪問
visitable = true
def __init__(self,value):
self.value = value
# 獲取當前節點頂部的 n 個子節點,先左後右
def gettopnodelist(self,n):
if n < 0:
return
p = self
pointlist =
left = true
for i in xrange(n):
if not isinstance(p,heaptree):
break
print p.value
p = pointlist[0]
pointlist.remove(p)
# 獲取最後乙個節點
def getlastnode(self):
pointlist = [self]
index = 0
while index < len(pointlist):
left = pointlist[index].leftchild
right = pointlist[index].rightchild
if left and left.visitable:
if right and right.visitable:
index += 1
lastnode = pointlist[-1]
return lastnode
# 展示結構
def show(self):
self._show(self,self.leftchild,"left")
self._show(self,self.rightchild,"right")
def _show(self,parent,child,desc=""):
if isinstance(child,heaptree):
print "%s %s: %s" % (parent.value,desc,child.value)
child.show()
# 堆排序
def sort(self):
self._sort()
while true:
lastnode = self.getlastnode()
lastnode.visitable = false
if lastnode == self:
return
self._swap(lastnode,self)
# 獲得初始堆,排序邏輯
def _sort(self):
if isinstance(self.leftchild,heaptree):
if not self.leftchild.visitable:
return
self.leftchild._sort()
self._swap(self,self.leftchild)
if isinstance(self.rightchild,heaptree):
if not self.rightchild.visitable:
return
self.rightchild._sort()
self._swap(self,self.rightchild)
# 交換父子節點的值
def _swap(self,parent,child):
if parent.value < child.value:
temp = parent.value
parent.value = child.value
child.value = temp
# 父子節點的值交換後,重新調整子節點結構
child._sort()
class treemanager(object):
def __init__(self,data):
self.data = data
# 建立頂堆樹
def bulidheaptree(self):
root = heaptree(self.data[0])
p = root
pointlist =
left = true
for i in self.data[1:]:
if left:
p.leftchild = heaptree(i)
else:
p.rightchild = heaptree(i)
p = pointlist[0]
pointlist.remove(p)
left = not left
self.heaptree = root
def show(self):
self.heaptree.show()
if __name__ == '__main__':
a = [2,3,4,1,5,6]
m = treemanager(a)
m.bulidheaptree()
h = m.heaptree
h.sort()
h.show()
h.gettopnodelist(8)
堆排序之 大頂堆
堆的定義 設有n個元素的序列 1 2 解釋 如果讓滿足以上條件的元素序列 建堆的步驟 從最後乙個非終端結點開始往前逐步調整,讓每個雙親大於 或小於 子女,直到根節點為止。注意 終端結點 即葉子 沒有任何子女,無需單獨調整。建堆的具體做法 1 將原始序列轉換成完全二叉樹。2 從序號最大的非葉子節點開始...
STL原始碼分析之大頂堆
關於大頂堆和小頂堆這裡就不再介紹了,這裡通過stl再次回顧一下。heap為了適應容器大小的不斷變化,底層呼叫vector實現 關於heap的演算法 這裡是大頂堆 push heap 演算法 為了滿足完全二叉樹的條件,新加入的元素一定是放在最下一層作為葉節點,並填補在由左至右的第乙個空格,即插在vec...
騷氣的Python之k means演算法
1.回顧 上次對驗證碼進行了去噪和灰度化,這次對它進一步地分類處理,這裡用顏色區分,顯然是分成4個類 2.關於演算法原理我就不多說,下面看 encoding utf 8 from pil import image import math import copy import random class...