Advertisement
Guest User

Untitled

a guest
Sep 22nd, 2017
59
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Lua 2.27 KB | None | 0 0
  1. function newHeap ()
  2.     heapObject = {}
  3.     heapObject.heap = {}
  4.     heapObject.len = 0 -- Size of the heap
  5.     function heapObject:push (newElement) -- Adds new element to the heap
  6.         local index = self.len
  7.         self.heap[index] = newElement -- Add to bottom of the heap
  8.         self.len = self.len + 1 -- Increase heap elements counter
  9.         self:heapifyUp(index) -- Maintane min heap
  10.     end
  11.  
  12.     function heapObject:heapifyUp (index)
  13.         local parentIndex = clamp(math.floor((index - 1) / 2), 0)
  14.         if self.heap[index].priority < self.heap[parentIndex].priority then
  15.             self.heap[index], self.heap[parentIndex] = self.heap[parentIndex], self.heap[index] -- Swap
  16.             self:heapifyUp(parentIndex) -- Continue sorting up the heap
  17.         end
  18.     end
  19.  
  20.     function heapObject:pop () -- Returns the element with the smallest priority
  21.         local minElement = self.heap[0]
  22.         self.heap[0] = self.heap[self.len - 1] -- Swap
  23.         -- Remove element from heap
  24.         self.heap[self.len - 1] = nil
  25.         self.len = self.len - 1
  26.         self:heapifyDown(0) -- Maintane min heap
  27.         return minElement
  28.     end
  29.  
  30.     function heapObject:heapifyDown (index)
  31.         local leftChildIndex = 2 * index + 1
  32.         local rightChildIndex = 2 * index + 2
  33.         if  (self.heap[leftChildIndex] and self.heap[leftChildIndex].priority < self.heap[index].priority)
  34.             or
  35.             (self.heap[rightChildIndex] and self.heap[rightChildIndex].priority < self.heap[index].priority) then
  36.                 if not self.heap[rightChildIndex] or self.heap[leftChildIndex].priority < self.heap[rightChildIndex].priority then
  37.                     self.heap[index], self.heap[leftChildIndex] = self.heap[leftChildIndex], self.heap[index] -- Swap
  38.                     self:heapifyDown(leftChildIndex) -- Continue sorting down the heap
  39.                 else
  40.                     self.heap[index], self.heap[rightChildIndex] = self.heap[rightChildIndex], self.heap[index] -- Swap
  41.                     self:heapifyDown(rightChildIndex) -- Continue sorting down the heap
  42.                 end
  43.         end
  44.     end
  45.  
  46.     function heapObject:root () -- Returns the root element without removing it
  47.         return self.heap[0]
  48.     end
  49.  
  50.     return heapObject
  51. end
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement