Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- function newHeap ()
- heapObject = {}
- heapObject.heap = {}
- heapObject.len = 0 -- Size of the heap
- function heapObject:push (newElement) -- Adds new element to the heap
- local index = self.len
- self.heap[index] = newElement -- Add to bottom of the heap
- self.len = self.len + 1 -- Increase heap elements counter
- self:heapifyUp(index) -- Maintane min heap
- end
- function heapObject:heapifyUp (index)
- local parentIndex = clamp(math.floor((index - 1) / 2), 0)
- if self.heap[index].priority < self.heap[parentIndex].priority then
- self.heap[index], self.heap[parentIndex] = self.heap[parentIndex], self.heap[index] -- Swap
- self:heapifyUp(parentIndex) -- Continue sorting up the heap
- end
- end
- function heapObject:pop () -- Returns the element with the smallest priority
- local minElement = self.heap[0]
- self.heap[0] = self.heap[self.len - 1] -- Swap
- -- Remove element from heap
- self.heap[self.len - 1] = nil
- self.len = self.len - 1
- self:heapifyDown(0) -- Maintane min heap
- return minElement
- end
- function heapObject:heapifyDown (index)
- local leftChildIndex = 2 * index + 1
- local rightChildIndex = 2 * index + 2
- if (self.heap[leftChildIndex] and self.heap[leftChildIndex].priority < self.heap[index].priority)
- or
- (self.heap[rightChildIndex] and self.heap[rightChildIndex].priority < self.heap[index].priority) then
- if not self.heap[rightChildIndex] or self.heap[leftChildIndex].priority < self.heap[rightChildIndex].priority then
- self.heap[index], self.heap[leftChildIndex] = self.heap[leftChildIndex], self.heap[index] -- Swap
- self:heapifyDown(leftChildIndex) -- Continue sorting down the heap
- else
- self.heap[index], self.heap[rightChildIndex] = self.heap[rightChildIndex], self.heap[index] -- Swap
- self:heapifyDown(rightChildIndex) -- Continue sorting down the heap
- end
- end
- end
- function heapObject:root () -- Returns the root element without removing it
- return self.heap[0]
- end
- return heapObject
- end
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement