Data structure: Priority queue

Source: Internet
Author: User
Tags comparable

Priority Queue (Java Edition) introduces priority queue Description:

    A priority queue is an abstract data type, which is a sort of mechanism that has two core operations: finding the element with the highest key value (top priority), inserting a new element, and the effect is that he is maintaining a dynamic queue .

You can collect some elements and quickly remove the elements with the largest key values , move them out of the queue after they have been manipulated, and then collect more elements , and then process the elements with the most current key values, and so on.

For example, we have a computer that can run multiple programs. The computer arranges the application according to priority by giving each application a priority attribute, and the computer always processes the next highest-priority element.

API for generic priority queues

  The most important action for a priority queue is to Delete the largest element and insert the element .

  

primary implementation of priority queuesArray implementations (unordered)

 Thought
We maintain an array , because the order of the arrays is not considered, so our insertion algorithm is simple.
For finding the maximum value, we took advantage of the selection sort , and after finding the maximum value, swapped it with the last element and made the length-1.
  ? Just give the simplest core implementation steps:

  PackageQueuedemo;  Public classQueueano<textendsComparable<t>> {        Privatet[] Array; Private intN;  PublicQueueano (intcapacity) {Array= (t[])NewComparable[capacity]; N=0; }        ........         Public voidInsert (T t) {Array[n]=t;n++; }         PublicT Delmax () {intMax=0;  for(inti=1;i<n;i++)//find the largest element            {                if(Less (max,i)) Max=i; } Exch (Max,n-1);//swap the largest element to the lastn--;//Length-1            returnArray[n]; }    }
array Implementation (ordered)

? Thought:
Since we maintain an ordered array , every time we insert an element, we have to find a suitable location to ensure that the array is ordered, and the delete operation will be simple.

  Code

 Public classOrderarraypriorityqueue <keyextendsComparable<key>>{    PrivateKey[] PQ;//Elements    Private intN//Number of elements     PublicOrderarraypriorityqueue (intcapacity) {PQ= (key[]) (Newcomparable[capacity]); N= 0; }     Public BooleanIsEmpty () {returnn = = 0; }     Public intSize () {returnN; }     PublicKey Delmax () {returnpq[--N]; }     Public voidInsert (key key) {inti = n-1;  while(I >= 0 &&Less (key, Pq[i])) {Pq[i+1] =Pq[i]; I--; } pq[i+1] =key; N++; }    Private BooleanLess (Key V, key W) {returnV.compareto (W) < 0; }     Public Static voidMain (string[] args) {Orderarraypriorityqueue<String> PQ =NewOrderarraypriorityqueue<string> (10); Pq.insert ("This"); Pq.insert ("Is"); Pq.insert (A); Pq.insert ("Test");  while(!Pq.isempty ())    System.out.println (Pq.delmax ()); }}
definition of a heap

Description
The two fork heap is good for the basic operation of the priority queue, and the two fork heap is a binary tree, but it is arranged according to a particular organizational structure .
That is, each element in the binary heap is guaranteed to be greater than or equal to the other two specific positions (child nodes).
Icon:
  

Description
  
This is a pile of ordered two-fork trees. The so-called heap order is a binary tree each node is greater than or equal to its two child nodes.

two fork stack notation:

? Let's organize an ordered two-fork tree, an orderly structure that allows us to implement a priority queue.
  
We can use pointers to represent them, but this is not the most convenient. By observing the two-forked ordered heap, we will find that it is a completely binary tree , and that a fully binary tree can be represented by an array.

  To implement a two-fork ordered heap with an array:

The specific method is to put the nodes of the two-fork tree into the array in sequence order , the root node position in 1, its child node position in 2,3.  

? Two important properties:  

1. In a binary heap, the parent node of the node with the position K is |_k/2_|, and its two child nodes are located at 2K and 2k+1
2. The height of a fully binary tree of size n is |_lgn_|

implementing priority queues with heaps ordered by the bottom-up heap

Description
 
If the stacking of a heap is broken because a node x becomes larger than its parent , we need to swap it and its parent node to fix the heap, but maybe the X is still very large after the swap, so we need X to compare its ancestor nodes over and over until we find the best place to hit it.
According to the nature of the binary heap, it is not difficult to find that it is simple to remember that the parent node of the node with location K is |_k/2_|.
Diagram

? code

Private void Swim (int  k) { while (k > 1 && less (K/2, K)) {   exch ( K/2, k);    = K/2;}}
ordered from top to bottom heap

Description
if the order of a heap is broken because a node x becomes smaller than its two child nodes or one of its nodes, we need to swap the larger nodes in it and its subnodes to fix the heap, but maybe the X is still small after the swap, so we need x to compare and exchange its child nodes over and over, Until you find the right place to hit it.
Diagram
  
? code

Private void sink (int  k) {        while// Last comparison            when its child nodes are leaf nodes int j = 2 * k;             if (J < N && Less (J, j + 1)) {                J++            ;            } if (! Less (k, J)) {                break;            }            Exch (k, j);             = J;        }    
Heap-based precedence sequences

Ideas
each time we insert an element into the end of the array, it may break the heap's ordering, so we float it .
When we remove and delete the largest element , the first position cannot be empty, and our practice is to move the last element to the first one and then to sink the operation .
In this way, we can give the complete code.

classMaxpq<keyextendsComparable<key>> {     Privatekey[] PQ; Private intN = 0;  PublicMAXPQ (intMAXN) {PQ= (key[])NewCOMPARABLE[MAXN + 1]; }      Public Static voidMain (string[] args) {MAXPQ<Integer> MAXPQ =NewMaxpq<integer> (10);  for(inti = 0; I < 10; i++) {Maxpq.insert (int) (Math.random () * 10 + 1)); }         while(!Maxpq.isempty ())        {System.out.println (Maxpq.delmax ()); }    }      Public intsize () {returnN; }      Public BooleanIsEmpty () {returnN = = 0; }      Public voidInsert (Key v) {pq[++n] =v;    Swim (N); }      Publickey Delmax () {Key Max= Pq[1]; Exch (1,n--); Pq[n+ 1] =NULL; Sink (1); returnMax; }     Private BooleanLessintIintj) {returnPq[i].compareto (Pq[j]) < 0; }     Private voidExch (intIintj) {Key temp=Pq[i]; Pq[i]=Pq[j]; PQ[J]=temp; }     Private voidSinkintk) { while(2 * k <=N) {intj = 2 *K; if(J < N && Less (J, j + 1) ) {J++; }            if(!Less (k, J)) {                 Break;            } Exch (k, J); K=J; }    }     Private voidSwimintk) { while(k > 1 && less (K/2, K)) {Exch (k/2, K); K= K/2; }    } } 

Data structure: Priority queue

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.