Go deep into Java Collection Series 5: PriorityQueue
Preface
Today, we will continue to analyze the source code implementation of PriorityQueue. In fact, in the Java Collection framework, there is ArrayDeque (a double-end Queue). Here we will analyze the source code of PriorityQueue. PriorityQueue is also called a priority queue. The so-called priority queue refers to the element obtained from the priority queue each time, either the maximum value (maximum heap) or the minimum value (minimum heap ). We know that a queue is a type of data structure that is first-in-first-out. Each time an element is removed from the queue header, an element is inserted from the end of the queue ), we can understand the queuing examples in our lives.
PriorityQueue description
The underlying data structure of PriorityQueue is "heap", which has the following two properties:
The value of any node is always not greater than (max heap) or smaller than (Min heap) the value of its parent node. The heap is a Complete Binary Tree.
The smallest heap used by the priority queue in Java means that each time the smallest element is retrieved from the queue, it is necessary to understand the number laws of the heap in order to better understand the source code. We know that no matter the heap or other data structures, they must be implemented using programming languages. In Java, the data structure of heap is basically an array, but this array is a bit special, the left and right child nodes of each element in the array also exist in the array. For any array subscript I, the following conditions are met:
Subscript left (I) = 2 * I of the left child node, right (I) = 2 * I + 1 of the right child node
In this way, you can put the complex tree elements in the data structure in a simple array. As long as you follow the above rules, you can easily find the left and right child nodes of any node. To solve the element storage problem, we need to restore the elements in the array to the heap. This is the heap building process, and the source code is based on the same idea. Taking adding an element to the heap as an example, Because array storage is used, the subscript of the newly added element is the last sub-value of the array, which corresponds to the last leaf node in the heap, because the newly added element destroys the heap nature, you need to adjust the newly added element so that it can be moved to the correct position to re-match the heap nature.
So the question is, where should I start building the heap? We noticed that the parent node of the last node is the largest node with the subscript of the child node, because the leaf node has no child node, based on this consideration, we chose the parent node of the last node as the starting point for heap building. For each node, the next step is to adjust the node location, this is the key to achieving the maximum or minimum heap. To clearly illustrate the heap building process, see the following:
The following uses elements {6, 5, 3, 1, 4, 8, 7} as an example to describe the specific process of heap construction:
If you think this process is too monotonous, you can refer to the dynamic diagram below. However, the dynamic diagram below also includes the heap sorting content. You only need to pay attention to the dynamic graph created earlier.
Now you should understand the specific heap building process. The following key is to add and remove elements. In order to combine PriZ elements? Http://www.bkjia.com/kf/ware/vc/ "target =" _ blank "class =" keylink "> vcml0ebXE1LTC68u1w/ejrM7SsNHV4rK/Signature =" Source code analysis "> source code analysis
Before analyzing and joining the team, let's take a look at how Java Source Code creates a heap?
// Create a heap private void heapify () {for (int I = (size> 1)-1; I> = 0; I --) siftDown (I, (E) queue [I]);} // insert element x in position k, to maintain the minimum heap nature, the node position is constantly adjusted. private void siftDown (int k, E x) {if (comparator! = Null) // adjust the node location siftDownUsingComparator (k, x) using the comparator implemented by the inserted element; else // use the default comparator (sort by nature) adjust the node location siftDownComparable (k, x);} // The specific function to adjust the node location private void siftDownComparable (int k, E x) {Comparable
Key = (Comparable
) X; // calculate the maximum position of a non-leaf node element. int half = size >>> 1; // loop while a non-leaf // if it is not a leaf node, it will keep repeating while (k ) C ). compareTo (E) queue [right])> 0) c = queue [child = right]; // If the node value to be inserted is smaller than its parent node, if (key. compareTo (E) c) <= 0) break; queue [k] = c; k = child;} // The loop ends, k is the leaf node queue [k] = key ;}
OK. Let's see how to add an element to a minimum heap:
Public boolean add (E e) {// call the offer function return offer (e);} // the code before siftUp mainly confirms that the queue capacity does not overflow, and save the number of elements in the queue and the number of structural/sexual modifications public boolean offer (E e) {if (e = null) throw new NullPointerException (); modCount ++; int I = size; if (I> = queue. length) grow (I + 1); size = I + 1; if (I = 0) queue [0] = e; else // execute the siftUp (I, e); return true;} // call different comparator to adjust the position of the element private void siftUp (int k, E x) {if (comparator! = Null) siftUpUsingComparator (k, x); else siftUpComparable (k, x);} // adjust the position of the element using the default comparator private void siftUpComparable (int k, E x) {Comparable
Key = (Comparable
) X; while (k> 0) {int parent = (k-1) >>> 1; // Save the value of the parent node Object e = queue [parent]; // use the compareTo method. if the element to be inserted is smaller than the parent node, the if (key. compareTo (E) e)> = 0) break; queue [k] = e; k = parent;} queue [k] = key ;} // call the implemented comparator to adjust the element position. The overall process is the same as above, that is, the comparison method is different private void siftUpUsingComparator (int k, E x) {while (k> 0) {int parent = (k-1) >>> 1; Object e = queue [parent]; // The compare method if (comparator. compare (x, (E) e)> = 0) break; queue [k] = e; k = parent;} queue [k] = x ;}
To better understand the execution process of the above Code, please refer to the following:
Team-out
An element is removed from the queue. Let's look at the implementation in the source code:
Private E removeAt (int I) {assert I> = 0 & I <size; modCount ++; // s is the queue header, corresponding to the last element in the array, int s = -- size; // if the position to be removed is the last one, set the last element to null if (s = I) // removed last element queue [I] = null; else {// Save the node Element E moved = (E) queue [s]; queue [s] = null; // first swap the last element with the I position, and then execute the siftDown (I, moved) method. // if the position remains unchanged after the method is lowered, it indicates that this element is the smallest element of the subtree. The raised party // method must be executed to keep the minimum heap property if (queue [I] = moved) {// The position is not siftUp (I, moved ); // Execute the raise method if (queue [I]! = Moved) // If the I position changes after the increase, return the return moved;} return null ;}
The above code will only execute one of the methods for raising and downgrading. For more information, see the following:
This is the method to be adjusted:
PriorityQueue Summary
After analyzing the source code above, the PriorityQueue is summarized as follows:
Time Complexity: the time complexity of the remove () and add () methods is O (logn), and the remove (Object obj) and contains () methods require O (n) time complexity, taking the team header requires O (1) Time to execute the heap building function during the initialization phase. The minimum heap is finally created. the ordering of the queue elements cannot be ensured for each outbound and inbound operations, only the order of the header and new inserted elements can be guaranteed. to output the elements in the queue in sequence, you only need to call Arrays. the sort () method can use the Iterator method to output the PriorityQueue element in the queue. To implement synchronization, you must call java. util. the PriorityBlockingQueue class under the concurrent package to implement synchronization. The null element is not allowed in the queue.