Python implementation of binary heap and Dagen

Source: Internet
Author: User

Python

Binary heaps (binary heap)

The binary heap is a special heap, the binary heap is a complete binary tree or is an approximate complete binary tree. The binary heap satisfies the heap characteristic: the parent node's key value always maintains a fixed order relation to the key value of any one child node, and the Saozi right subtree of each node is a binary heap.
The maximum heap when the parent node's key value is always greater than or equal to the key value of any one of the child nodes. The minimum heap when the parent node's key value is always less than or equal to the key value of any one of the child nodes.

Storage of binary piles

A binary heap is generally represented by an array. If the position of the root node in the array is 1, the nth-position child nodes are at 2n and 2n+1 respectively. Therefore, the child nodes of the 1th position are at 2 and 3, and the 2nd position of the child nodes is at 4 and 5. And so on This 1-based array storage facilitates the search for parent and child nodes.
If the subscript of the storage array is based on 0, then the child nodes of the node labeled I are 2i + 1 and 2i + 2; What is the subscript of the parent node? Floor (I? 1) ∕2), function floor (x), its function is "rounding down", or "rounded down", that is, the largest integer not greater than X (and " Rounding "is different, the next rounding is directly on the axis on the nearest required value of the left value, that is, not greater than the maximum value of the required value). For example Floor (1.1), floor (1.9) is returned 1.
such as the two heaps:

Save the two heaps in an array that starts with 1:
Position: 1 2 3 4 5 6 7 8 9 10 11
Left: 1 2 3 4 5 6 7 8 9 10 11
Right: 11 9 10 5 6 7 8 1 2 3 4
For a large heap, this kind of storage is inefficient. Because a node's child nodes are likely to be in another memory page. B-heap is a more efficient way to store each subtree on the same memory page.
If you use a pointer-linked list to store the heap, you need a way to access the leaf nodes. You can traverse these nodes sequentially by "threading" (threading) The two-fork tree.

Basic Operation Insert Node

Inserts a new node at the very end of the array. Then the child node is adjusted from the bottom to the parent node (called Up-heap or bubble-up, percolate-up, sift-up, trickle Up, heapify-up, cascade-up operation): Compares the current node to the parent node, The exchange is not satisfied with the heap nature. So that the current subtree satisfies the properties of the binary heap. The time complexity is O (log n).

Delete a node

Delete the root node for heap sorting.
For the largest heap, deleting the root node deletes the maximum value, and for the minimum heap, the minimum value is removed. Then, move the last node of the heap storage to fill it at the root node. Then adjust the parent node and its child nodes from top to bottom: for the largest heap, if the parent node is smaller than the child node with the maximum value, the two are exchanged. This operation is called Down-heap or Bubble-down, Percolate-down, Sift-down, trickle down, heapify-down, Cascade-down,extract-min/max, etc. Until the current node and its child nodes satisfy the heap nature.

Constructing a two-fork heap

An intuitive approach is to start with a single-node two-fork heap, inserting one node at a time. It has a time complexity of {\displaystyle O (n\log N)} o (N\log N).
The optimal algorithm starts with a two-fork tree arbitrarily placed from a node element, and the max-heapify algorithm (which is for the largest heap) that executes when the root node is deleted from the bottom up of each subtree makes the current subtree a binary heap. In particular, assuming that the height of H-subtree has completed two fork heap, then for the height of the h+1 subtree, the root node along the maximum sub-nodes of the branch to adjust, up to the H-step to complete two fork heap. It can be proved that the time complexity of this algorithm is O (n).

Code
#!/usr/bin/env Python2#-*-Coding:utf-8-*-"""@author: Gsharp"""classBinaryheap:def __init__( Self, N): Self. Heap=[0]*N Self. Size= 0    defRemove_min ( Self): Removed=  Self. heap[0] Self. Size-= 1         Self. heap[0]=  Self. heap[ Self. Size] Self. _down (0)returnRemoveddefAdd Self, value): Self. heap[ Self. Size]=Value Self. _UP ( Self. Size) Self. Size+= 1    def_UP ( Self, POS): whilePos> 0: Parent=(POS- 1)// 2            if  Self. Heap[pos]>=  Self. Heap[parent]: Break             Self. Heap[pos], Self. heap[parent]=  Self. Heap[parent], Self. Heap[pos] Pos=Parentdef_down ( Self, POS): while True: Child= 2 *Pos+ 1            ifChild>=  Self. Size: Break            ifChild+ 1 <  Self. Size and  Self. heap[child+ 1]<  Self. Heap[child]: Child+= 1            if  Self. Heap[pos]<=  Self. Heap[child]: Break             Self. Heap[pos], Self. Heap[child]=  Self. Heap[child], Self. Heap[pos] Pos=ChilddefTest (): H=Binaryheap (Ten) H.add (5) H.add (7) H.add (9) H.add (4) H.add (3)Print(H.HEAP) H.add (1)Print(H.HEAP) H.add (2)Print(H.HEAP)Print(H.remove_min ())Print(H.remove_min ())Print(H.remove_min ()) test ()

Python implementation of binary heap and Dagen

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.