Created
March 10, 2018 14:02
-
-
Save LasseJacobs/95b60edacad73463cf0131a3111ca433 to your computer and use it in GitHub Desktop.
Python heapsort (As descirbed in Introduction to Algorithms)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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