#!/usr/bin/env python#-*-coding:utf-8-*-ImportHEAPQImportCopyImportdatetimeImportRandomdefGet_max_heap (heap, size, root):#make structural adjustments in the heap so that the parent node value is greater than the child node Left= 2 * root + 1 Right= left + 1larger=RootifLeft < size andHeap[larger] < Heap[left]:#ensure that the maximum value is not reorderedlarger = LeftifRight < Size andHeap[larger] < Heap[right]:#ensure that the maximum value is not reorderedlarger = RightifLarger! = Root:#If a heap adjustment is made, the value of the larger is equal to the left or right node, and this is the time to perform a value reversal operationHeap[larger], heap[root] =Heap[root], Heap[larger] get_max_heap (heap, size, larger)defbuild_heap (heap):#construct a heap to reorder all data in the heap forIndexinchXrange (len (heap)/2-1,-1,-1):#start with the first non-leaf nodeget_max_heap (Heap, Len (heap), index)defsort (heap): Build_heap (heap)#get a big top pile forIndexinchXrange (Len (heap)-1,-1,-1): Heap[0], Heap[index]= Heap[index], heap[0]#adjust the maximum value to the lastGet_max_heap (heap, index, 0)#size is decremented to ensure that the maximum value is not reordered returnHeapif __name__=='__main__': #A = eval (raw_input (' Please enter a list to be sorted \ n '))A = [Random.randint (1, 2000) forIinchRange (1000)] B=Copy.deepcopy (a) B_begin=Datetime.datetime.now () sort (b) B_end=Datetime.datetime.now ()Print 'My method Use%s'% (B_end-b_begin). Total_seconds () C=Copy.deepcopy (a) C_begin=Datetime.datetime.now () heapq.heapify (c) C_end=Datetime.datetime.now ()Print 'Inner method use%s'% (C_end-c_begin). Total_seconds () —————————————————————————————— my method use0.011Inner method use 0.001
#可以看到, the sorting algorithm we implement is less time-heapq.heapify ()
Python implementations of Heap ordering