Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

More Simple Kiss BinHeap #13

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
65 changes: 31 additions & 34 deletions trees/binheap.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,58 +7,55 @@
# this heap takes key value pairs, we will assume that the keys are integers
class BinHeap:
def __init__(self):
self.heapList = [0]
self.heapList = []
self.currentSize = 0


def buildHeap(self,alist):
i = len(alist) // 2
self.currentSize = len(alist)
self.heapList = [0] + alist[:]
print(len(self.heapList), i)
while (i > 0):
print(self.heapList, i)
self.heapList = alist[:]

i = len(alist)//2 -1
while (i >= 0):
self.percDown(i)
print(i, self.heapList)
i = i - 1
print(self.heapList,i)

def percDown(self,i):
while (i * 2) <= self.currentSize:
mc = self.minChild(i)
if self.heapList[i] > self.heapList[mc]:
tmp = self.heapList[i]
self.heapList[i] = self.heapList[mc]
self.heapList[mc] = tmp
i = mc

def minChild(self,i):
if i * 2 + 1 > self.currentSize:
return i * 2
else:
if self.heapList[i * 2] < self.heapList[i * 2 + 1]:
return i * 2
heapList = self.heapList
while True:
child = 2*i+1
if child >= self.currentSize:
break
if child+1<self.currentSize and heapList[child+1] < heapList[child]:
child += 1
if heapList[i] > heapList[child]:
# swap
heapList[i],heapList[child] = heapList[child],heapList[i]
else:
return i * 2 + 1
break
i = child

def percUp(self,i):
while i // 2 > 0:
if self.heapList[i] < self.heapList[i//2]:
tmp = self.heapList[i // 2]
self.heapList[i // 2] = self.heapList[i]
self.heapList[i] = tmp
i = i // 2

heapList = self.heapList
while (i-1) // 2 >= 0:
parent = (i-1)//2
if heapList[i] < heapList[parent]:
heapList[i], heapList[parent] = heapList[parent],heapList[i]
else:
break
i = parent

def insert(self,k):
self.heapList.append(k)
self.currentSize = self.currentSize + 1
self.percUp(self.currentSize)
self.percUp(self.currentSize-1)

def delMin(self):
retval = self.heapList[1]
self.heapList[1] = self.heapList[self.currentSize]
retval = self.heapList[0]
self.heapList[0] = self.heapList[self.currentSize-1]
self.currentSize = self.currentSize - 1
self.heapList.pop()
self.percDown(1)
self.percDown(0)
return retval

def isEmpty(self):
Expand Down