I am using MinHeap to sort my cake order. The bakery shop will always prepare an order with the nearest delivery date/time.
Result:
Order(s): [['02012022 1300', 165720252206939, 'Black Forest', 1.0, 90, 'New'], ['01012023 1500', 16572025295153491, 'Black Forest', 2.0, 160, 'New'], ['01012023 0900', 1657202554873902, 'Oreo Brownie', 1.0, 110, 'New'], ['02012022 0900', 16572025920151477, 'Cheese Cake', 1.0, 110, 'New']]
Index 0 in the first array is the delivery date/time. However, my orders are not sorted correctly. Based on the result, the orders are just added into the last index of the array. I need the orders to be sorted according to the nearest date/time. Please help! Many Thanks!
What I have tried:
class MinHeap:
def _init_(self):
self.size = 0
self.heap_list = []
self.queue = Queue()
def leftchild_index(self, index):
return 2 * index + 1
def rightchild_index(self, index):
return 2 * index + 2
def parent_index(self, index):
return (index - 1)
def has_leftchild(self, index):
return self.leftchild_index(index) < self.size
def has_rightchild(self, index):
return self.rightchild_index(index) < self.size
def has_parent(self, index):
return self.parent_index(index) >= 0
def left_child(self, index):
return self.heap_list[self.leftchild_index(index)]
def right_child(self, index):
return self.heap_list[self.rightchild_index(index)]
def parent(self, index):
return self.heap_list[self.parent_index(index)]
def swap(self, index1, index2):
temp = self.heap_list[index1]
self.heap_list[index1] = self.heap_list[index2]
self.heap_list[index2] = temp
def insert(self, data):
self.heap_list.append(data)
self.size += 1
self.heapify_up()
print('Order added! ')
print("Order(s): ", self.heap_list, "\n")
def heapify_up(self):
index = 0
while self.has_parent(index) and self.parent(index) > self.heap_list[index]:
self.swap(self.parent_index(index), index)
index = self.parent_index(index)