Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
18 changes: 14 additions & 4 deletions heaps/heap_sort.py
Original file line number Diff line number Diff line change
@@ -1,8 +1,18 @@

from heaps.min_heap import MinHeap

def heap_sort(list):
""" This method uses a heap to sort an array.
Time Complexity: ?
Space Complexity: ?
Time Complexity: O (n log n)
Space Complexity: O (1)
"""
pass
heap = MinHeap()
for num in list:
heap.add(num)

index = 0
while not heap.empty():
list[index]=heap.remove()
index +=1
return list


56 changes: 44 additions & 12 deletions heaps/min_heap.py
Original file line number Diff line number Diff line change
Expand Up @@ -19,21 +19,31 @@ def __init__(self):
def add(self, key, value = None):
""" This method adds a HeapNode instance to the heap
If value == None the new node's value should be set to key
Time Complexity: ?
Space Complexity: ?
Time Complexity: O(1)
Space Complexity: O(n)
"""
pass
if value == None:
value = key

node = HeapNode(key, value)
self.store.append(node)
self.heap_up(len(self.store)-1)


def remove(self):
""" This method removes and returns an element from the heap
maintaining the heap structure
Time Complexity: ?
Space Complexity: ?
Time Complexity: O(1)
Space Complexity: O(1)
"""
pass
if len(self.store)== 0:
return None



self.swap(0, len(self.store)-1)
min = self.store.pop()
self.heap_down(0)
return min.value

def __str__(self):
""" This method lets you print the heap, when you're testing your app.
"""
Expand All @@ -47,8 +57,8 @@ def empty(self):
Time complexity: ?
Space complexity: ?
"""
pass

if len(self.store)== 0:
return True

def heap_up(self, index):
""" This helper method takes an index and
Expand All @@ -60,15 +70,37 @@ def heap_up(self, index):
Time complexity: ?
Space complexity: ?
"""
pass
if index == 0:
return

parent_index =(index-1)//2
store = self.store

if store[parent_index].key > store[index].key:
self.swap(parent_index, index)
self.heap_up(parent_index)

def heap_down(self, index):
""" This helper method takes an index and
moves the corresponding element down the heap if it's
larger than either of its children and continues until
the heap property is reestablished.
"""
pass
left_child = index * 2 + 1
right_child = index * 2 + 2
store = self.store
if left_child < len(self.store):
if right_child < len(self.store):
if store[left_child].key < self.store[right_child].key:
smaller = left_child
else:
smaller = right_child
else:
smaller = left_child

if store[index].key > store[smaller].key:
self.swap(index, smaller)
self.heap_down(smaller)


def swap(self, index_1, index_2):
Expand Down