Skip to content

Commit 2d8a3b4

Browse files
committed
Add Big O time complexity
1 parent 6a937b4 commit 2d8a3b4

File tree

1 file changed

+11
-2
lines changed

1 file changed

+11
-2
lines changed

pygorithm/data_structures/heap.py

Lines changed: 11 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -22,11 +22,14 @@ def insert(self, data):
2222

2323
def heapify_up(self):
2424
'''
25-
Start at the end of the tree (first enqueued item).
25+
Start at the end of the tree (last enqueued item).
2626
2727
Compare the rear item to its parent, swap if
2828
the parent is larger than the child (min-heap property).
2929
Repeat until the min-heap property is met.
30+
31+
Best Case: O(1), item is inserted at correct position, no swaps needed
32+
Worst Case: O(logn), item needs to be swapped throughout all levels of tree
3033
'''
3134
child = self.rear
3235
parent = self.parent_idx(child)
@@ -37,7 +40,7 @@ def heapify_up(self):
3740
parent = self.parent_idx(child)
3841

3942
def pop(self):
40-
''' Removes the lowest value element (highest priority) from the heap '''
43+
''' Removes the lowest value element (highest priority, at root) from the heap '''
4144
min = self.dequeue()
4245
if self.rear >= 1: # heap may need to be fixed
4346
self.heapify_down()
@@ -64,6 +67,9 @@ def heapify_down(self):
6467
6568
While a favorite child exists, and that child is smaller
6669
than the parent, swap them (sift down).
70+
71+
Best Case: O(1), item is inserted at correct position, no swaps needed
72+
Worst Case: O(logn), item needs to be swapped throughout all levels of tree
6773
'''
6874
cur = ROOT = 0 # start at the root
6975
fav = self.favorite(cur) # determine favorite child
@@ -76,6 +82,9 @@ def heapify_down(self):
7682
else:
7783
return
7884

85+
def time_complexities(self):
86+
return '''[Insert & Pop] Best Case: O(1), Worst Case: O(logn)'''
87+
7988
def get_code(self):
8089
''' returns the code for the current class '''
8190
import inspect

0 commit comments

Comments
 (0)