Deep understanding of Java Priorityqueue

Source: Internet
Author: User

Deep understanding of Java Priorityqueuepriorityqueue

This article GitHub address

In Java, Priorityqueue is implemented by a binary small top heap, which can be represented by a complete binary tree. Starting from the queue interface function and combining vivid illustrations, this paper analyzes the specific process and time complexity of each operation in Priorityqueue, which will allow the reader to establish a clear and in-depth understanding of priorityqueue.

General Introduction

In front of Java Arraydeque as an example to explain the Stack and queue, in fact, there is a special queue called Priorityqueue, that is, priority queue. the role of the priority queue is to ensure that each element taken out is the lowest weight in the queue (the Java priority queue takes the smallest element at a time, and the priority queue of C + + takes the largest element at a time). This involves the size of the relationship, the size of the element can be judged by the natural order of the elements themselves (natural ordering), can also be constructed by the comparator (Comparator, similar to C + + copy function).

In Java, Priorityqueue implements the Queue interface, does not allow the element to be placed, null and is implemented through the heap, specifically througha fully binary tree (complete binary trees). The small top heap (the weights of any non-leaf nodes are not much more than the weights of their left and right nodes), which means that they can be used as the bottom-level implementations of Priorityqueue by arrays.

We give each element in the way of sequence traversal, if you are careful enough, you will find that the parent node and child nodes are linked, more specifically, the number of parent-child node has the following relationship:

leftNo = parentNo*2+1

rightNo = parentNo*2+2

parentNo = (nodeNo-1)/2

With the above three formulas, it is easy to calculate the parent node of a node and the subscript of the child node. This is why you can use arrays to store heaps directly.

priorityqueue peek() and element operations are constant time, and the add() time complexity of the offer() parameterless remove() and poll() the method is log (N).

Method anatomy Add () and offer ()

add(E e)offer(E e)the same semantics are inserted into the priority queue, except that the interface specifies that the two Queue handles the insertion failure, which throws an exception when the insert fails, and then returns false . There is no difference between the two methods of Priorityqueue .

The newly added elements may break the nature of the small top heap, so the necessary adjustments need to be made.

Offer (e e)Public Boolean Offer(e) {if (E = =NullNull element not allowedthrow new nullpointerexception (); modCount ++; int i = size; if (i >= queue.grow (i + 1); //automatic expansion size = i + 1; if (i = = 0)  //queue was originally empty, this is the first element inserted Queue[0] = e; else siftup (i, e);  //adjustment return true;}               

In the above code, the expansion function grow() is similar to ArrayList the function inside, that is, the application of grow() a larger array, and the original array of elements copied past, here no longer repeat. It is important to note that the siftUp(int k, E x) method is used to insert elements x and maintain the properties of the heap.

Siftup ()Private void siftup (int< Span class= "Hljs-params" > K, E x) {while (k > 0) {int parent = (K-1) >>> 1;//parentno = (nodeNo-1)/2 Object e = queue[parent]; if (Comparator.0) //Call Comparator comparison method break; queue[k] = e; k = parent;} Queue[k] = x;}      

The newly added elements x may break the nature of the small top heap and therefore need to be adjusted. The process of adjustment is : k starting at the specified position, the x layer is compared and exchanged with the current point parent , until it x >= queue[parent] is satisfied . Note that the comparison here can be either the natural order of the elements or the order of the comparators.

Element () and peek ()

element()And peek() The semantics are exactly the same, is to get but not delete the first element of the queue, that is, the lowest weight of the element, the only difference is when the method fails when the former throws an exception, the latter returns null . According to the nature of the small top heap, the element at the top of the heap is the smallest one in the world; because the heap is represented by an array, the element at the subscript is 0 both the top element of the heap, according to the subscript relationship. So just return 0 to the element at the subscript of the array .

The code is also very concise:

//peek()public E peek() { if (size == 0) return null; return (E) queue[0];//0下标处的那个元素就是最小的那个}
Remove () and poll ()

remove()and poll() The semantics of the method are exactly the same, is to get and delete the first element of the team, the difference is when the method fails when the former throws an exception, the latter returns null . Because the delete operation changes the structure of the queue, the necessary adjustments are needed to maintain the nature of the small top heap.


The code is as follows:

PublicEpoll () {if (size = = 0) return null; int s =--size; modcount++; E result = (e) queue[0];//0 the element at the bottom is the smallest E x = (e) queue[s]; Queue[s] = null; if (s! = 0) siftdown ( 0, X); //adjust return result;}   

The code above first records the element at the subscript, replaces the element at the subscript 0 position with the last element 0 , and then calls the siftDown() method to adjust the heap, returning the element at the original subscript 0 (that is, the smallest element). The focus is on the siftDown(int k, E x) method, which k starts at the specified position, and then x swaps down to the smaller of the children in the right and left of the current point, until it is x less than or equal to any one of the children.

Siftdown ()Private void Siftdown(IntK, E x) {int half = size >>>1;while (K < half) {//first find the smaller of the left and right children, record it in C, and use child to record its subscript int child = (k << 1) + 1; //leftno = parentno*2+1 Object c = queue[child]; int right = child + 1; if (Right < size && Comparator.0) c = Queue[child = right]; if (Comparator.0) break; queue[k] = C;//then substituting C for the original value k = child;} Queue[k] = x;}        
Remove (Object o)

remove(Object o)The Collection method is used to delete an element in the queue that is o equal to the equivalent (if there are multiple equals, delete only one), and the method is not a method inside the queue interface, but rather a method of the interface. Because the delete operation changes the queue structure, it is adjusted, and because the location of the deleted element may be arbitrary, the adjustment process is a bit more cumbersome than the other functions. Specifically, there are remove(Object o) 2 scenarios: 1. The last element is deleted. Delete directly, no need to adjust. 2. Delete the last element, starting at the point where the last element is invoked once for the reference siftDown() . Do not repeat here.

The specific code is as follows:

Remove (Object o)Public Boolean Remove(Object o) {Find the first subscript that satisfies the o.equals (Queue[i]) element by iterating through the arrayint i =IndexOf (o);if (i = =-1) return FALSE; int s =--size; if (s = = i) //situation 1 Queue[i] = null; else {e moved = (e) queue[s]; Queue[s] = null; siftdown (I, moved); //situation 2 ...} return true;} 

http://www.cnblogs.com/CarpenterLee/p/5488070.html

In-depth understanding of Java Priorityqueue

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.