Advertisement
Guest User

Untitled

a guest
Feb 23rd, 2019
63
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.89 KB | None | 0 0
  1.  
  2. class Heap(object):
  3.  
  4. HEAP_SIZE = 10
  5.  
  6. def __init__(self):
  7. self.heap = [0]*Heap.HEAP_SIZE;
  8. self.currentPosition = -1;
  9.  
  10. def insert(self, item):
  11.  
  12. if self.isFull():
  13. print("Heap is full..");
  14. return
  15.  
  16. self.currentPosition = self.currentPosition + 1
  17. self.heap[self.currentPosition] = item
  18. self.fixUp(self.currentPosition)
  19.  
  20. def fixUp(self, index):
  21.  
  22. parentIndex = int((index-1)/2)
  23.  
  24. while parentIndex >= 0 and self.heap[parentIndex] < self.heap[index]:
  25. temp = self.heap[index]
  26. self.heap[index] = self.heap[parentIndex]
  27. self.heap[parentIndex] = temp
  28. index=parentIndex
  29. parentIndex = (int)((index-1)/2)
  30.  
  31. def heapsort(self):
  32.  
  33. for i in range(0,self.currentPosition+1):
  34. temp = self.heap[0]
  35. print("%d " % temp)
  36. self.heap[0] = self.heap[self.currentPosition-i]
  37. self.heap[self.currentPosition-i] = temp
  38. self.fixDown(0,self.currentPosition-i-1)
  39.  
  40. def fixDown(self, index, upto):
  41.  
  42. while index <= upto:
  43.  
  44. leftChild = 2*index+1
  45. rightChild = 2*index+2
  46.  
  47. if leftChild < upto:
  48. childToSwap = None
  49.  
  50. if rightChild > upto:
  51. childToSwap = leftChild
  52. else:
  53. if self.heap[leftChild] > self.heap[rightChild]:
  54. childToSwap = leftChild
  55. else:
  56. childToSwap = rightChild
  57.  
  58. if self.heap[index] < self.heap[childToSwap]:
  59. temp = self.heap[index]
  60. self.heap[index] = self.heap[childToSwap]
  61. self.heap[childToSwap] = temp
  62. else:
  63. break
  64.  
  65. index = childToSwap
  66. else:
  67. break;
  68.  
  69. def isFull(self):
  70. if self.currentPosition == Heap.HEAP_SIZE:
  71. return True
  72. else:
  73. return False
  74.  
  75.  
  76. if __name__ == "__main__":
  77.  
  78. heap = Heap()
  79. heap.insert(10)
  80. heap.insert(-20)
  81. heap.insert(0)
  82. heap.insert(2)
  83. heap.insert(4)
  84. heap.insert(5)
  85. heap.insert(6)
  86. heap.insert(7)
  87. heap.insert(20)
  88. heap.insert(15)
  89.  
  90. heap.heapsort()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement