Python implementations of Heap ordering

Source: Internet
Author: User

#!/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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.