1. Overview
The heap (also called the precedence queue) is a complete binary tree, which is characterized by the value of the parent node being greater than (less than) two child nodes (called a large top heap and a small top heap, respectively). It is often used to manage the information during the execution of the algorithm, including heap ordering, priority queue, etc.
2. Basic operation of the heap
The heap is a complete binary tree with a height of O (LG N), whose basic operation is proportional to the height of the tree. Before introducing the basics of the heap, let's introduce a few basic terms:
A: The array to represent the heap, with the subscript starting at 1 and all the time to n
Parent (T): node T's parents node, that is, floor (T/2)
Right (T): node T's left child node, that is: 2*t
Left (T): node T's right child node, that is: 2*t+1
Heap_size (a): Heap A current number of elements
The main four operations are given below (for example, in the case of a large top heap):
2.1 Heapify (A,N,T)
This operation is mainly used to maintain the basic properties of the heap. A subtree with the root of right (T) and left (T) is assumed to be a heap, and then the subtree with T as the root is adjusted to make it a heap. 1 2 3 4 5 6 7 8 9 (int a[], int n, int t) {int left = = heapify. Left (t); int right = right (t); int max = t; if (left <= n) max = A[left] > A[max]? Left:max; if (right <= n) max = A[right] > A[max]? Right:max; if (Max!= a[t]) {swap (A, Max, T); Heapify (A, N, max); } }
2.2 Buildheap (A,n)