Skip to content

Instantly share code, notes, and snippets.

@cbdavide
Created December 30, 2016 20:02
Show Gist options
  • Save cbdavide/3135e432075c5401f92016b071da6277 to your computer and use it in GitHub Desktop.
Save cbdavide/3135e432075c5401f92016b071da6277 to your computer and use it in GitHub Desktop.
Heap sort algorithm, using the binary heap, and bitmask operators
class Heap:
def __init__(self, arr):
self.cont = arr
self.size = len(self.cont) - 1
self.buildheap()
def left(self, i):
return (i << 1) + 1
def right(self, i):
return (i << 1) + 2
def parent(self, i):
return (i - 1) >> 1
def buildheap(self):
for i in range(self.size >> 1, -1, -1):
self.heapify(i)
def heapify(self, i):
l = self.left(i)
r = self.right(i)
largest = i
if l <= self.size and self.cont[l] > self.cont[i]:
largest = l
if r <= self.size and self.cont[r] > self.cont[largest]:
largest = r
if largest != i:
self.cont[i], self.cont[largest] = self.cont[largest], self.cont[i]
self.heapify(largest)
def heapsort(arr):
h = Heap(arr)
for i in range(h.size, 0, -1):
h.cont[0], h.cont[i] = h.cont[i], h.cont[0]
h.size -= 1
h.heapify(0)
return h.cont
if __name__ == '__main__':
arr = [5, 13, 2, 25, 7, 17, 20, 8, 4]
print(heapsort(arr))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment