Binary heap of data structures (heap)

Source: Internet
Author: User

Note: This section focuses on the maximum heap (least-heap empathy).
first, the concept of the heapHeap, also known as a two-pronged heap. Like the binary search tree, the heap has two properties, namely, structure and heap order. 1. Structural Properties:The heap is a fully filled two-fork tree, with the possible exception being at the bottom, where elements from left to right fill in. Such trees are called full binary trees (complete binary tree).        is one such example. For a complete binary tree, there are some properties: (1), a full binary tree of high H, which contains 2^h ~ (2^ (h+1)-1) nodes.    That is, the height of the complete binary tree is [Logn], which is obviously O (Logn). (2), a complete binary tree can be used to structure the expression of an array:

Index

0

1

2

3

4

5

6

7

8

9

10

11

12

13

Value


A

B

C

D

E

F

G

H

I

J





A careful look at the index of the array and the distribution of the elements in the tree, you can get: for a ternary two-fork tree, the tree structure and array index have the following relationship: Leftchild.index = 2 * PARENT.INDEX;     Rightchild.index = 2 * parent.index + 1; (3), through the previous discussion, we can look at a heap of data structures: An array, the size of the current heap heaplen. 2, the nature of the heap sequence:The nature of the fast execution of operations is the heap order.    Sequencing properties: In a heap, the key word in the father of each node x,x is greater than (or equal to) the keyword in x, except for the root node (it has no parent). Depending on the nature of the heap sequence, the maximum element can always be found at the root.    Therefore, we complete the find operation with constant time. Comparison: Heap-ordered properties: Heaps with no stacking properties:
Second, basic heap operationDeclaration: int heap[max+1]; int Heaplen; The size of the heap
int Leftele (int i) {return i*2;}    int Rightele (int i) {return i*2+1;}    int Parentele (int i) {return I/2;} void swap (int i, int j) {int tmp;TMP = i, i = j, j = tmp; }
1. Query operation:    int Findmax () {return heap[1]; }
Function Resolution: The maximum value of a heap is the root node element, which is returned directly to the value.
2, heap maintenance operations: Sinking Operation:    void maxheapify (int i)     {        int ileft = Leftele (i);    //Find this section Left son of Point         int iright = Rightele (i);    //Find the node's right son         int largest = i;    //Record maximum node, initial node self                //Find the maximum corresponding node     & nbsp   if (ILeft < Heaplen && Heap[i] < Heap[ileft])             largest = ILe ft;        if (IRight < Heaplen && Heap[largest] < Heap[iright])       &NB Sp     largest = iright;               //swaps the node corresponding to the maximum value of the original node and then heap on the switched node Maintenance actions         if (largest! = i)         {            SWA P (Heap[i], heap[largest]);            Maxheapify (largest);       }&NBS P  }
3, build the heap operation:     Before we give concrete instructions on how to build a heap, we can look at how it should be implemented.    Now given a heap (which should not be called a heap), the heap is constructed from the initial array, and its structure is: Obviously this is not the largest heap. The entire array is:    
Index 83 11 6 15 36 19
Value 1 2 3 4 5 6
After a series of operations, we need to convert the heap to: the entire maximum heap process is this:maintain heap operations from bottom to top. First, find the first node that has a subtree, perform a heap maintenance operation on that node, and then go up to heap maintenance. Here's the question: where is the first node with a subtree? ===>>>>> for a complete binary tree, the leaf node must be stored at the end of the array, and now the question is how many leaf nodes are there? Once you know the number of leaf nodes, it is easy to determine the location of the nodes with the subtree.    So how many of the leaf nodes are there?    Complete binary tree has a total of n nodes, leaf nodes have n0, because the number of nodes of the binary tree is the maximum of 2, so can be set to 1 of the node is N1, the number of degrees 2 is N2.    So we can get a couple of these relationships: N0+N1+N2 = n;    n-1 = 2*n2 + n1; (two different representations of the number of sides) to solve this equation, you can get: N0 = (n+1-n1)/2.    For a complete binary tree, n1 = 1 or 0 when n1=1, N0=N/2; n0= (n+1)/2 when n1=0.    So we can get the leaf node is half the total number of nodes.    Thus, a non-leaf node should be the first half of the array.        ===>>> void Buildheap () {int i;    for (i = HEAPLEN/2; i > 0; i--) maxheapify (i); }
4. Sort operation:     The key to     heap sequencing is to swap the maximum elements to the end of the array and re-perform the heap maintenance operations. Loop the operation sequentially, that is, you can get the sorted array.     void Heapsort ()     {        int i;        buileheap () &nbs P       for (I=heaplen; i>=1; i--)         {            s WAP (Heap[heaplen], heap[1]);            heaplen--;            Maxheapify (1);       }   }        function parsing:    First we start with heap ordering To sort the elements in an array:
23 1 16 9 54
The heap is now sorted: A, build heap: B, Exchange 54 and 1, and unbind the last element of the heap from the original heap: C, refactor the heap: D, in turn, the loop finally gets:    In this way, the array becomes:
1 9 16 23 54
This completes the sorting of the array.
5. Insert element operation: Insert Insertheap (): This action is the push operation in the priority queue. Before you introduce a specific insert operation, you need to implement the Increasekey (int i, int key) function to update the heap structure. Floating Operation:void Increasekey (int i, int key) {assert (key >= heap[i]);        Assert that the key value is greater than heap[i], if not, then terminate and error heap[i] = key;            while (i > 1 && heap[parentele (i)] < Heap[i]) {swap (Heap[i], Heap[parentele (i)]);        i = Parentele (i);    }} Here, you need to focus on the specific steps of the increasekey operation, for example: For such a heap, the value of node 6 is increased from 8 to 54->>>: The entire operation is Increasekey (6, 54).        The whole process is as follows: So the code to insert the element into the heap is as follows: void insertheap (int x) {heaplen++;        Heap[heaplen] =-inf;    Increasekey (Heaplen, x); } 6. Delete element operation:Delete Deleteheapmax (): Equivalent to the pop () operation in the priority queue.        int Deleteheapmax () {int ret = heap[1];        Swap (ret, heap[heaplen]);        heaplen--;        Maxheapify (1);    return ret; }
third, the algorithm analysis:
Query operations O (1)
Heap Maintenance operations O (LOGN)
Build heap Operations O (NLOGN)
Heap Sort Operations O (NLOGN)


From for notes (Wiz)

Binary heap of data structures (heap)

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.