Created
March 25, 2014 05:34
-
-
Save reillyeon/9755764 to your computer and use it in GitHub Desktop.
Min heaps are one of my favorite data structures.
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
class MinHeap(object): | |
def __init__(self): | |
self.a = [] | |
def insert(self, value): | |
self.a.append(value) | |
i = len(self.a) - 1 | |
parent = (i - 1) // 2 | |
while i != 0 and self.a[parent] > self.a[i]: | |
self.a[parent], self.a[i] = self.a[i], self.a[parent] | |
i = parent | |
parent = (i - 1) // 2 | |
def remove(self): | |
if len(self.a) == 0: | |
return None | |
elif len(self.a) == 1: | |
return self.a.pop() | |
value = self.a[0] | |
self.a[0] = self.a.pop() | |
i = 0 | |
while True: | |
left = 2 * i + 1 | |
right = 2 * i + 2 | |
smallest = i | |
if left < len(self.a) and self.a[smallest] > self.a[left]: | |
smallest = left | |
if right < len(self.a) and self.a[smallest] > self.a[right]: | |
smallest = right | |
if smallest != i: | |
self.a[i], self.a[smallest] = self.a[smallest], self.a[i] | |
i = smallest | |
else: | |
break | |
return value | |
def heapsort(a): | |
h = MinHeap() | |
for x in a: | |
h.insert(x) | |
for i in range(len(a)): | |
a[i] = h.remove() | |
if __name__ == '__main__': | |
import random | |
h = MinHeap() | |
a = [random.randint(0, 100) for _ in range(10)] | |
heapsort(a) | |
print(a) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment