The priority queue, as its name implies, is inserted into the corresponding position when the element is joined by the priority queue, compared to the traditional "advanced out" queue. In fact, the priority queue Priotyqueue in poll or follow the advanced-out, but the data in the entry has been sorted by priority. Implementing a priority queue requires implementing a comparator with the following test code:
public class Priotyqueuetest {
Comparator, used to determine the priority of two elements comparator<man> t = new comparator<man> () { @Override public int Compare ( Mans O1, man O2) { if (o1.getage () = = O2.getage ()) return 0; if (O1.getage () > O2.getage ()) return 1; return-1; } }; queue<man> queue = new priorityqueue<man> (11,t);
Adds the given array to the priority queue public void Add (int[] nums) {for (int i = 0; i < nums.length; i++) Queue.add (The New Man (Stri Ng.valueof (i), nums[i])); }
print function public void print () { while (Queue.peek ()!=null) { System.out.println (Queue.poll (). Getage () + ""); } System.out.println (); } public static void Main (string[] args) { int[] test = new int[]{5,4,2,3,1}; Priotyqueuetest q = new Priotyqueuetest (); Q.add (test); Q.print (); }}
Test entity class man{ private String name; private int age; Public Mans (String Name,int age) { this.name = name; This.age = age; } Public String GetName () { return name; } public void SetName (String name) { this.name = name; } public int getage () { return age; } public void Setage (int.) { this.age = age; }}
To my curiosity, what exactly happened in the Add () function here? Let's take this part of the source code out review:
private void Siftupusingcomparator (int k, E x) {while (k > 0) { int parent = (k-1) >>> 1;<span s Tyle= "White-space:pre" ></span>//subscript right one bit, equivalent to except 2 Object e = Queue[parent];<span style= "White-space:pre "></span>//Gets the parent node if (Comparator.compare (x, (e) e) >= 0) <span style=" White-space:pre "></span >//comparison, if the priority is greater than the parent node, stop searching for break ; Queue[k] = e; K = parent; } QUEUE[K] = x; }
From the above code we can see:
1, the queue is based on the object array implementation, and abstract into a tree structure;
2, the meaning of the comparator here is: until the priority is less than the element to stop the search;
3. The time complexity of the deletion is O (1), the insertion time complexity is O (n)
Java Priority Queue Priotyqueue