def heapFullTest(): """ Various tests for Heap class, using both MinHeaps and MaxHeaps, including sorting and random operations. """ print("Testing MinHeap: sorting") for i in range(1, 21): if heapRandomSort(250, True): print "Test", i, "successful" else: print "Test", i, "failed" print("\nTesting MaxHeap: sorting") for i in range(1, 21): if heapRandomSort(250, False): print "Test", i, "successful" else: print "Test", i, "failed" print("\nTesting MinHeap: general") for i in range(1, 21): if heapRandomTest(250, True): print "Test", i, "successful" else: print "Test", i, "failed" print("\nTesting MaxHeap: general") for i in range(1, 21): if heapRandomTest(250, False): print "Test", i, "successful" else: print "Test", i, "failed" print("\nTesting MinHeap: other operations") ar = [1, 4, 501, -200, 32, 7, 65, -1, 20000, -34, 17] min_heap = MinHeap() min_heap.createMinHeap(ar) print min_heap.extractMin() print min_heap.extractMin() print min_heap.extractMin() max_heap = MaxHeap() max_heap.createMaxHeap(ar) print max_heap.extractMax() print max_heap.extractMax() print max_heap.extractMax() print "Max: ar", max( ar), "min_heap", min_heap.maximum(), "max_heap", max_heap.maximum() print "Min: ar", min( ar), "min_heap", min_heap.minimum(), "max_heap", max_heap.minimum()
def heapSort1(nums): n = len(nums) maxheap = MaxHeap() for i in xrange(n): maxheap.insert(nums[i]) for i in xrange(n - 1, -1, -1): nums[i] = maxheap.extractMax()
def printKBestCandidates(self, k=None): if k is None: k = len(self._candidates) from heap import MaxHeap c: Candidate # for c in self._candidates: # print(c) h = MaxHeap(len(self._candidates)) for c in self._candidates: h.insert(c) result_number = len( self._candidates) if len(self._candidates) < k else k for i in range(result_number): print(h.extractMax())
def heapSort2(nums): n = len(nums) maxheap = MaxHeap() maxheap.heapify(nums) for i in xrange(n - 1, -1, -1): nums[i] = maxheap.extractMax()