Priority queue

Keywords: data structure queue

catalogue

Priority queue

concept

Characteristics of priority queues

Note when using priority queues:  

Construction of priority queue

Operation implementation of priority queue  

 

Priority queue

concept

First, a queue is a first in, first out (FIFO) Data structure of , but in some cases, The data of the operation may have priority and is generally out of the queue Column, you may need to first get out of the queue for elements with high priority In this scenario, it is obviously inappropriate to use queues. For example, when playing games on the mobile phone, if there is an incoming call, the system should give priority to the incoming call. In this case, our data structure should provide two basic operations, one is to return the highest priority object, and the other is to add a new object . This data structure is called priority queue (Priority Queue) .

Characteristics of priority queues

Java The collection framework provides PriorityQueue and PriorityBlockingQueue Two types of priority queues, PriorityQueue It's a line It's not safe, PriorityBlockingQueue Is thread safe

Note when using priority queues:  

1. When using, you must import the package where PriorityQueue is located, that is:

import java.util.PriorityQueue;
2. PriorityQueue Placed in The element must be able to compare the size, and cannot insert objects that cannot compare the size, otherwise it will be thrown
ClassCastException abnormal
3. No insert null Object, otherwise it will be thrown NullPointerException
4. There is no capacity limit. You can insert any number of elements, and the internal capacity can be expanded automatically
5. The time complexity of inserting and deleting elements is O(log ν N)
6. PriorityQueue Heap data structure is used in the bottom layer
7. PriorityQueue Small heap by default --- That is, the element obtained each time is the smallest element  

Construction of priority queue

Here are just a few common construction methods in PriorityQueue

constructor Function introduction
PriorityQueue()
Create an empty priority queue with a default capacity of 11
PriorityQueue(int
initialCapacity)
Create an initial capacity of initialCapacity Note: initialCapacity cannot be less than 1 Otherwise, Ill will be thrown egalArgumentException abnormal
PriorityQueue(Collection<?
extends E> c)
Use a collection to create priority queues
static void TestPriorityQueue(){
       // Create an empty priority queue with the default capacity of 11
       PriorityQueue<Integer> p1 = new PriorityQueue<>();
       // Create an empty priority queue with the underlying capacity of initialCapacity
       PriorityQueue<Integer> p2 = new PriorityQueue<>(100);
       List<Integer> list = new ArrayList<>();
       list.add(4);
       list.add(3);
       list.add(2);
       list.add(1);
       // Use the ArrayList object to construct a priority queue object
       PriorityQueue<Integer> p3 = new PriorityQueue<>(list);
       System.out.println(p3.size());//size = 4
       System.out.println(p3.peek());//peek = 1
}
Note: by default, PriorityQueue The queue is a small heap. If a large heap is needed, the user needs to provide a comparator
// User defined Comparator: directly implement the Comparator interface, and then rewrite the compare method in the interface
class IntCmp implements Comparator<Integer>{
    public int compare(Integer o1, Integer o2) {
    return o2-o1;
    }
}
public class TestPriorityQueue {
    public static void main(String[] args) {
    PriorityQueue<Integer> p = new PriorityQueue<>(new IntCmp());
    p.offer(4);
    p.offer(3);
    p.offer(2);
    p.offer(1);
    p.offer(5);
    System.out.println(p.peek());//peek = 5
    }
}

At this point, a lot is created.

Operation implementation of priority queue  

Priority queue is a collection of 0 or more elements. Each element has a priority. The operations performed on the priority queue are (1) find (2) insert a new element (3) delete   Generally, the find operation is used to search for the element with the highest priority, and the delete operation is used to delete the element. Elements with the same priority can be processed in first in first out order or according to any priority.

Function nameFunction introduction
boolean offer(E e)
Insert element e , successful insertion returned true , if e Object is empty, throw NullPointerException Exception, time complexity O(log ν N). Note: capacity expansion will be carried out when there is not enough space
E peek()
Gets the element with the highest priority. If the priority queue is empty, returns null
E poll()
Remove the element with the highest priority and return. If the priority queue is empty, return null
int size()
Get the number of valid elements
void clear()
empty
boolean isEmpty()
Check whether the priority queue is empty. If it is empty, return true
static void TestPriorityQueue2(){
    int[] arr = {4,1,9,2,8,0,7,3,6,5};
    PriorityQueue<Integer> q = new PriorityQueue<>(arr.length);
    for (int i = 0; i < arr.length; i++) {
        q.offer(i);
    }
    System.out.println(q.size()); // Number of valid elements in the print priority queue
    System.out.println(q.peek()); // Gets the element with the highest priority
    // Delete two elements from the priority queue and get the element with the highest priority again
    q.poll();
    q.poll();
    System.out.println(q.size()); // Number of valid elements in the print priority queue
    System.out.println(q.peek()); // Gets the element with the highest priority
    q.offer(0);
    System.out.println(q.peek()); // Gets the element with the highest priority
    // Delete the valid elements in the priority queue and check whether they are empty
    q.clear();
    if(q.isEmpty()){
       System.out.println("Priority queue is already empty");
    }else{
       System.out.println("Priority queue is not empty");
    }
}
Here is In JDK 1.8, Description of priority queue expansion:
  • If the capacity is less than 64, it is expanded in the way of twice the oldCapacity
  • If the capacity is greater than or equal to 64, it is expanded by 1.5 times the oldCapacity
  • If the capacity exceeds MAX_ARRAY_SIZE, according to MAX_ARRAY_SIZE for capacity expansion
private static final int MAX_ARRAY_SIZE = Integer.MAX_VALUE - 8;

private void grow(int minCapacity) {
   int oldCapacity = queue.length;
   // Double size if small; else grow by 50%
   int newCapacity = oldCapacity + ((oldCapacity < 64) ? (oldCapacity + 2) : (oldCapacity >> 1));
   // overflow-conscious code
   if (newCapacity - MAX_ARRAY_SIZE > 0)
       newCapacity = hugeCapacity(minCapacity);
   queue = Arrays.copyOf(queue, newCapacity);
}

private static int hugeCapacity(int minCapacity) {
   if (minCapacity < 0) // overflow
       throw new OutOfMemoryError();
   return (minCapacity > MAX_ARRAY_SIZE) ? Integer.MAX_VALUE : MAX_ARRAY_SIZE; 
}

Posted by Lambneck on Thu, 11 Nov 2021 22:10:14 -0800