Skip to content

Instantly share code, notes, and snippets.

@LasseJacobs
Created March 10, 2018 14:02
Show Gist options
  • Save LasseJacobs/95b60edacad73463cf0131a3111ca433 to your computer and use it in GitHub Desktop.
Save LasseJacobs/95b60edacad73463cf0131a3111ca433 to your computer and use it in GitHub Desktop.
Python heapsort (As descirbed in Introduction to Algorithms)
def swap(a, i, j):
a[i], a[j] = a[j], a[i]
def left(i):
return 2*i + 1
def right(i):
return 2*i + 2
def max_heapify(array, i, h_size):
l = left(i)
r = right(i)
if l < h_size and array[l] > array[i]:
largest = l
else:
largest = i
if r < h_size and array[r] > array[largest]:
largest = r
if largest != i:
swap(array, i, largest)
max_heapify(array, largest, h_size)
def build_max_heap(array):
for i in reversed(range(0, int(len(array)/2))):
max_heapify(array, i, len(array))
def heap_sort(array):
build_max_heap(array)
heap_size = len(array)
for i in reversed(range(1, len(array))):
swap(array, 0, i)
heap_size = heap_size - 1
max_heapify(array, 0, heap_size)
t = [5, 1, 7, 3, 6, 4, 2]
heap_sort(t)
print(t)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment