Created
May 19, 2014 20:08
-
-
Save sean-duffy/62b0447fc9ba0c3b3971 to your computer and use it in GitHub Desktop.
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 parent(i): | |
return (i + 1) / 2 - 1 | |
def left(i): | |
return (i + 1) * 2 - 1 | |
def right(i): | |
return ((i + 1) * 2) | |
def insert(heap, n): | |
heap.append(n) | |
i = len(heap) - 1 | |
while n < heap[parent(i)]: | |
heap[i] = heap[parent(i)] | |
i = parent(i) | |
heap[i] = n | |
def delete_min(heap): | |
heap[0], heap[-1] = heap[-1], heap[0] | |
heap_min = heap.pop() | |
i = 0 | |
while (heap[i] > heap[left(i)] or heap_min > heap[right(i)]) and heap[left(i)] != None and heap[right(i)] != None: | |
if heap[left(i)] < heap[right(i)]: | |
heap[left(i)], heap[i] = heap[i], heap[left(i)] | |
i = left(i) | |
else: | |
heap[right(i)], heap[i] = heap[i], heap[right(i)] | |
i = right(i) | |
if left(i) >= len(heap) or right(i) >= len(heap): | |
if left(i) >= len(heap): | |
break | |
else: | |
if heap[i] > heap[left(i)]: | |
heap[left(i)], heap[i] = heap[i], heap[left(i)] | |
break | |
return heap_min | |
heap = [2, 5, 4, 11, 14, 10, 6, 12, 25, 15] | |
insert(heap, 3) | |
assert heap == [2, 3, 4, 11, 5, 10, 6, 12, 25, 15, 14] | |
assert delete_min(heap) == 2 | |
assert heap == [3, 5, 4, 11, 14, 10, 6, 12, 25, 15] |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment