class Empty:
pass
class Heap:#实现递增排序
def __init__(self,list=[]):
self._data=list
self._cur=len(self._data)-1
def _parent(self,j):#返回父节点
return (j-1)//2
def _left(self,j):#返回左孩子节点
return 2*j+1
def _right(self,j):#返回右孩子节点
return 2*j+2
def _has_left(self,j,lens):
return self._left(j)<lens
def _has_right(self,j,lens):
return self._right(j) < lens
def _swap(self,i,j):
self._data[i],self._data[j]=self._data[j],self._data[i]
def _upheap(self,j):
parent=self._parent(j)
if j>0 and self._data[j]>self._data[parent]:
self._swap(j,parent)
self._upheap(parent)
def _downheap(self,j):
if self._has_left(j,self._cur+1):
left=self._left(j)
bigchild=left
if self._has_right(j,self._cur+1):
right=self._right(j)
if self._data[right]>self._data[left]:
bigchild=right
if self._data[bigchild]>self._data[j]:
self._swap(bigchild,j)
self._downheap(bigchild)
def heaporder(self):
while self._cur!=0:
start=self._parent(self._cur)
for i in range(start,-1,-1):
self._downheap(i)
self._swap(0,self._cur)
self._cur-=1
def print_list(self):
for i in self._data:
print(i,end=' ')
list=[3,4,5,7,11,100,1,2,6,7,7,1,1000]
heap=Heap(list)
heap.heaporder()
heap.print_list()
python-堆排序
最新推荐文章于 2023-08-05 13:56:03 发布