Vi. sequencing of Heaps
Heap sorting is a tree-select sort, which is an effective improvement on direct selection sequencing.
Heap definition: A sequence with n elements (h1,h2,..., HN), when and only if satisfied (hi>=h2i,hi>=2i+1) or (hi<=h2i,hi<=2i+1) (i=1,2,..., N/2) is called a heap. Only the heap that satisfies the former condition is discussed here. As can be seen from the definition of a heap, the top element of the heap (that is, the first element) must be the largest (large top heap). A fully binary tree can represent the structure of a heap visually. Heap top is the root, the other is Zuozi, right subtree.
Basic idea: the sequence of numbers to be sorted is initially treated as a two-fork tree of sequential storage, which adjusts their storage order to become a heap, when the heap has the largest number of root nodes. The root node is then exchanged with the last node of the heap. The number of fronts (n-1) is then re-adjusted to make it a heap. And so on, until there are only two nodes of the heap, and exchange them, and finally get an ordered sequence of n nodes. In terms of algorithm description, heap sequencing requires two processes, one is to build the heap, and the other is the last element of the heap to exchange the position. So the heap sort has two functions. One is to build the seepage function of the heap, and the second is to call the function of the infiltration function to realize the sorting.
Algorithm implementation:
#Coding:utf-8#!/usr/bin/pythonImportRandomImportMath#randomly generate a value between 0~100defget_andomnumber (num): Lists=[] I=0 whilei<num:lists.append (random.randint (0,100)) I+=1returnlists#Adjustment Heapdefadjust_heap (lists, I, size): Lchild= 2 * i + 1Rchild= 2 * i + 2Max=IifI < SIZE/2: ifLchild < size andLists[lchild] >Lists[max]: Max=LchildifRchild < size andLists[rchild] >Lists[max]: Max=RchildifMax! =I:lists[max], Lists[i]=Lists[i], Lists[max] adjust_heap (lists, max, size)#Create Heapdefbuild_heap (lists, size): forIinchRange (0, (int (SIZE/2))) [::-1]: adjust_heap (lists, I, size)#Heap Sortdefheap_sort (lists): Size=len (lists) build_heap (lists, size) forIinchRange (0, size) [::-1]: lists[0], Lists[i]=Lists[i], Lists[0] adjust_heap (lists, 0, i)returnListsa= Get_andomnumber (10)Print("before sorting:%s"%a) b=Heap_sort (a)Print("after sorting:%s"%b
Nine sorting algorithms you need to know heap sort of "python implementation"