Skip to content

Instantly share code, notes, and snippets.

@smaspe
Created July 11, 2017 02:29
Show Gist options
  • Save smaspe/60594f5dafe9e381fd0264289e172b9a to your computer and use it in GitHub Desktop.
Save smaspe/60594f5dafe9e381fd0264289e172b9a to your computer and use it in GitHub Desktop.
A quick implementation of heapsort
parent_index = lambda x: (x - 1) / 2
left_child_index = lambda x: 2 * x + 1
def heapsort(arr):
"""
sorts the given list using heapsort
"""
heapify(arr)
print_heap(arr)
sort_heap(arr)
def heapify(arr):
"""
turns list arr into a heap
"""
cnt = len(arr)
for current in range(parent_index(cnt - 1), -1, -1):
sift_down(arr, current, cnt)
def sort_heap(arr):
"""
turns the heap into a sorted list
"""
end = len(arr)
while end > 0:
arr[0], arr[end - 1] = arr[end - 1], arr[0]
end -= 1
sift_down(arr, 0, end)
print_heap(arr[:end])
def sift_down(arr, root, end):
"""
fix the heap
"""
while left_child_index(root) < end:
left = left_child_index(root)
swap = root
if arr[left] > arr[swap]:
swap = left
if left + 1 < end and arr[left + 1] > arr[swap]:
swap = left + 1
if swap == root:
return
arr[root], arr[swap] = arr[swap], arr[root]
root = swap
a = [6,4,7,1,2,5,8,9,3]
from math import log
def print_heap(heap):
start = 0
end = 1
print('heap')
while start < len(heap):
spaces = ' ' * ((len(heap) * 2) / (end - start + 1))
print(spaces + spaces.join(str(i) for i in heap[start:end]))
start = end
end = (end * 2) + 1
print('end of heap')
heapsort(a)
print(a)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment