diff --git a/heaps/heap_sort.py b/heaps/heap_sort.py index 3b834a5..d79cf63 100644 --- a/heaps/heap_sort.py +++ b/heaps/heap_sort.py @@ -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 \ No newline at end of file + heap = MinHeap() + for num in list: + heap.add(num) + + index = 0 + while not heap.empty(): + list[index]=heap.remove() + index +=1 + return list + + diff --git a/heaps/min_heap.py b/heaps/min_heap.py index f6fe4e0..d542e7a 100644 --- a/heaps/min_heap.py +++ b/heaps/min_heap.py @@ -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. """ @@ -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 @@ -60,7 +70,15 @@ 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 @@ -68,7 +86,21 @@ def heap_down(self, index): 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):