Two fork Pile
12 definition of a fork heap
The heap is a fully binary tree structure (except for the bottom layer, the other layers are completely balanced), and if each node is greater than its two children, then the heap is ordered.
A binary heap is a set of elements that can be ordered by a complete binary tree in a heap order and stored in the array in the hierarchy (without the first position of the array)
22 properties of fork piles
- The largest element in a[1] (root node)
- Every k's father in K/2
- Every k's child in K*2 and k*2+1
32 operation of a fork heap
3.1 Ascent (child greater than father)--corresponding insert operation
Cycle, compare yourself and father each time, if bigger than the father in exchange, until root.
3.2 inserting
First add the element to the last position of the array and then float to the correct position.
3.3 Sinking (father smaller than son)--corresponding delete operation
Cycle, each comparison of their own and two children, if smaller than the child in exchange, if compared to two children are small, exchange to two of the larger one. Until the leaves.
3.4 Deleting the largest element
First swap the root element with the last element, delete the last element, and then sink from the root to the correct position.
42 Fork Heap Priority Queue Code
/** * * @author Rocky * * Public class MAXPQ<key extends comparable<key> > { PrivateKey[] PQ;Private intN Public MAXPQ(intcapacity) {PQ = (key[])NewComparable[capacity +1]; } Public Boolean IsEmpty() {returnN = =0; } Public void Insert(Key key) {n++; Pq[n] = key; Swim (N); } PublicKeyDelmax() {Key max = pq[1];//get the max elementExch (1+ i);//exchange between the root and the last elementn--; Sink1);//sink to the right placepq[n+1] =NULL;//delete returnMax }Private void Swim(intK) { while(k >1&& Less (k/2, k)) {exch (k, k/2); K/=2; } }Private void Sink(intK) { while(k*2<= N)//if This node have left child{intChild = k *2;if(Child < N && less (child, child +1)) {//if the left than theChild = child +1;//change Child to the right child}if(Less (k, child)) {Exch (k, child); } k = child; } }Private Boolean Less(intIintj) {returnPq[i].compareto (Pq[j]) <0; }Private void Exch(intIintj) {Key t = pq[i]; Pq[i] = Pq[j]; PQ[J] = t; }}
52 Fork Heap Expansion
5.1 non-denatured
The premise of our algorithm is that the user will not change the elements of the queue, if the user can change the elements of the queue, then the condition of the queue will be destroyed,
Immutable data types, which means that once an instance is established, it cannot be changed. Many of the types in Java are immutable.
There are many benefits, but the downside is that if you need to change the value you must create a new object.
"Algorithms algorithm" Note: Priority queue (2)--Two fork heap