How to Implement heap sorting in Python and how to implement python heap sorting

Source: Internet
Author: User

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 

Related Article

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.