How to Implement heap sorting in Python and how to implement python heap sorting
This example describes how to implement heap sorting in Python. We will share this with you for your reference. The details are as follows:
Heap sorting is a basic sorting method. Similar to merging and sorting, unlike inserting sorting, it runs at O (nlogn), like inserting sorting instead of merging and sorting, it is an in-situ sorting algorithm, which only occupies the space of constant elements except the input array.
Heap (Definition ):The heap data structure is an array object, which can be regarded as a Complete Binary Tree. If the value of the root node is greater than (less than) All other nodes, and its left and right subtree also meets this nature, the heap is a large (small) Root heap.
Let's assume that A heap is represented by array A, and A [1] is the root of the tree. Given the subscript I of A node, the cursor of its parent node, left child, and right child can be calculated as follows:
PARENT (I ):
Return I/2
LEFT (I ):
Return 2i
RIGHT (I ):
Return 2i + 1
Python Implementation of heap sorting
The so-called heap sorting process is to gradually establish a heap process for unordered objects.
The following is the heap Sorting Code implemented in Python:
Def build_max_heap (to_build_list): "Create a heap" "# create a heap from the bottom up for I in range (len (to_build_list)/2-1,-1, -1): max_heap (to_build_list, len (to_build_list), I) def max_heap (to_adjust_list, heap_size, index ): "adjust the elements in the list to ensure that the index-based heap is the largest Heap" "# compare the current node with its left and right subnodes, exchange large nodes with the current node, and recursively adjust the subtree left_child = 2 * index + 1 right_child = left_child + 1 if left_child