"Data Structure" heap

Source: Internet
Author: User

Heap

this data structure. The general heap is used to implement the priority queue. Priority queue: As with the usual stack and queue, except that each element inside has a "priority", in the process of processing, first of all the highest priority. Typically consists of three operations Getmax/delmax/insert

Stacks and queues are special cases of priority queues.

The use of other data structures cannot be done simultaneously with the complexity of O (LGN). There is at least one operation that takes time O (NLGN). For example, the insert operation of the list O (1), but to get the maximum value must traverse the linked list.

You can use BBST above three operations to achieve the best time complexity O (LGN). In fact, there is no need to use such a high-end data structure to achieve such a simple function, because this is only the three simple functions.

So the heap of this data structure emerged.

The heap is logically a completely binary tree (the balance factor is a non-negative AVL tree), which is physically directly aided by vectors (variable groups), and therefore has vector-shaped, tree-gods.

A heap is a parent-child relationship defined between elements of a vector.

Maximum heap: The value of all nodes is less than or equal to the parent node, and the minimum heap is vice versa. As a maximum heap, here I take the largest heap as an example.


Construct such a data structure, the time complexity of the above three interfaces are O (h), because the tree height of the complete binary tree is O (LGN), so the time complexity of Getmax,delmax,insert is O (LGN)

In the following code I do not use vectors, but I maintain an array, can achieve the same effect.

implementation of the heap

public class Heap {private static int PARENT (int i) {return (i-1) >>1;} private static int Left (int i) {return 1+ (i<<1);} private static int Right (int i) {return (i+1) <<1;} Private int[] Heaparray;private int n;public Heap (int max_size) {Heaparray = new int[max_size];} /** * Gets the maximum value in the heap * @return */public int Getmax () {if (n = = 0) {throw new Indexoutofboundsexception ();} return heaparray[0];} /** * Delete the maximum value in the heap */public void Deletemax () {if (n = = 0) {throw new Indexoutofboundsexception ();} Heaparray[0] = heaparray[n-1];n--;p ercolatedown (0);} /** * Insert operation * @param e */public void Insert (int e) {heaparray[n++] = E;//percolateup (n-1);p Ercolateuprecu (n-1);} /** * Overflow * @param target indicates the subscript of the element to be overflowed */private void percolateup (int target) {//Full binary Tree high control on O (LGN) overflow time complexity O (LGN) 3l GN----> Lgn+2int parent = parent (target), while (Target > 0) {//target overflows up to root if (Heaparray[target] <= Heaparray[pa Rent]) Break;swap (Heaparray, parent, target); target = Parent;parent = parent (target);}} /** * Recursive overflow * @Param Target represents the subscript of the element to be overflowed */private void Percolateuprecu (int target) {if (Target > 0) {if (Heaparray[target] > he Aparray[parent (target)] {swap (Heaparray, parent (target), target);p Ercolateuprecu (parent (target));}} /** * Filter * @param target indicates the subscript of the element to be filtered */private void Percolatedown (int target) {int maxindex = Maxofthree (heaparray,ta Rget); while (target! = Maxindex) {//When target is not the largest in comparison with two children, it has been under filter swap (Heaparray, maxindex, target); target = Maxindex; Maxindex = Maxofthree (Heaparray, target);}} /** * Floyd create heap bottom-up filtering complexity is O (n) sum height (i) * @param heaparr */public void Createheapfloyd (int [] heaparr) {System.arr Aycopy (Heaparr, 0, Heaparray, 0, heaparr.length); n = heaparr.length;for (int i = (n-1) >> 1; I >= 0; i--) {perc Olatedown (i);}} /** * Create heap top-down overflow complexity O (NLGN) sum depth (i) * @param heaparr */public void Createheap (int[] heaparr) {//for (int i:heap ARR) {//insert (i);//}//more compact notation system.arraycopy (Heaparr, 0, Heaparray, 0, heaparr.length); n = heaparr.length;for (int i = 0; I < n; i++) {percolateup (i);}} /** * Gets the target and its two children the largest subscript of the corresponding value * @param heaparray * @param target * @return return target and its two children the largest subscript */private int ma of the corresponding value Xofthree (int[] heaparray, int target) {//compare target and the size of his two children, return the largest subscript//valid subscript cannot exceed n-1int left = left (target);//> N-1? Integer.MIN_VALUE:LEFT (target); int right = right (target); > n-1? Integer.MIN_VALUE:RIGHT (target); int max = Target;if (left<=n-1) {max = Heaparray[left] > Heaparray[max]? left:m AX;} if (right<=n-1) {max = Heaparray[right] > Heaparray[max]? Right:max;} return Max;} private void Swap (int[] heaparray, int i, int j) {int temp;temp = Heaparray[i];heaparray[i] = Heaparray[j];heaparray[j] = temp;}}

The specific meanings of each of these methods have been commented in detail.

Correlation Algorithm

The following algorithms for overflow and down filtering and the algorithm for creating heaps are made to explain.

Overflow

When inserting a new element, we first place the new element at the end of the array, and then compare it to the logical Father node, if it is larger than the parent node, it repeats the interchange until the maximum heap condition is met or has been swapped to the root location, specifically to refer to


Down filter

When deleting one of the largest elements, the first element in the heap, we first put the last element in the heap in the first place, and then compare it to the logical child node, and if it is smaller than the child node, it repeats the exchange with the largest child node until the maximum heap condition is met or No child is

The filtering operation can also be understood as the process of merging two small maximum heaps into a large maximum heap by inserting an element. The specific can be referenced


Create Heap

The code above lists two ways to create the largest heap

1. Top-Down overflow

public void Createheap (int[] heaparr) {system.arraycopy (Heaparr, 0, Heaparray, 0, heaparr.length); n = heaparr.length;for (int i = 0; i < n; i++) {Percolateup (i);}}

Traverses all the elements in the heap and overflows them. So there are n elements, and the time complexity of each element overflow is O (LGN). So time complexity is t (n) =O (NLGN)

In fact, the complexity of the time is t (n) = n∑depth (i), we know that more than half of the complete binary tree is the leaf node depth is O (LGN), so T (N) is also nlgn order of magnitude.

2. Bottom-down filtering

public void Createheapfloyd (int [] heaparr) {system.arraycopy (Heaparr, 0, Heaparray, 0, heaparr.length); n = heaparr.lengt h;for (int i = (n-1) >> 1; I >= 0; i--) {Percolatedown (i);}}

Filter operation we use it when we delete the largest element in the heap, but it can also be understood to be the process of merging two small maximum heaps into a large maximum heap.

It can actually be used in a built-in heap operation.

As a result of a complete binary tree from subscript (n-1)/2+1 is the leaf node. So each leaf node can be called a maximum heap of only one element. Therefore, the lower standard (n-1)/2 Starts the reverse filter operation.

The time complexity of this algorithm is t (n) =O (n). In fact, the time complexity is detailed for t (n) = (n-1)/2∑height (i) =o (n)

The more nodes The complete binary tree is, the more the first algorithm is linear with the depth and the second algorithm is linearly related to the height, obviously, the complexity is much smaller than the first one.

"Data Structure" 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.