Thinking logic of computer programs (46) and thinking 46
The previous section introduces the basic concepts and algorithms of heap. In this section, we will discuss the specific implementation class PriorityQueue of heap in Java.
Let's start with the basic concepts, introduce its usage, analyze the implementation code, and summarize and analyze its features.
Basic Concepts
As the name suggests, PriorityQueue is a priority Queue, which first implements the Queue interface (Queue). Similar to the Queue list, it has no Queue length limit. The difference between PriorityQueue and general queues is that, it has the concept of priority, each element has a priority, and the element of the team header is always the highest priority.
PriorityQueue is implemented in a heap. The internal elements are not completely ordered. However, if you leave the queue one by one, you will get ordered output.
Although the name is a priority queue, PriorityQueue can also be considered as a general data structure that implements the heap nature. You can use PriorityQueue to solve the problem that is suitable for the heap solution, in the next section, we will look at some specific examples.
Basic usage
Queue Interface
PriorityQueue implements the Queue interface. We have introduced Queue in the Queue list section. To facilitate reading, we will repeat its definition here:
public interface Queue<E> extends Collection<E> { boolean add(E e); boolean offer(E e); E remove(); E poll(); E element(); E peek();}
The Queue extends the Collection. There are three main operations:
- Add (add, offer) elements at the end)
- View the element (peek) of the header, and return the element of the header without changing the queue.
- Delete the Header element (remove, poll), return the Header element, and delete it from the queue.
Constructor
PriorityQueue has multiple constructor methods, as shown below:
public PriorityQueue()public PriorityQueue(int initialCapacity)public PriorityQueue(int initialCapacity, Comparator<? super E> comparator)public PriorityQueue(Collection<? extends E> c)public PriorityQueue(PriorityQueue<? extends E> c)public PriorityQueue(SortedSet<? extends E> c)
PriorityQueue is implemented by heap. The heap is an array physically. Similar to ArrayList, PriorityQueue uses dynamic arrays and dynamically scales based on the number of elements. initialCapacity indicates the initial array size, you can pass in parameters. For the default constructor, initialCapacity uses the default value 11. For the last three constructor methods, they accept an existing Collection, and the array size is equal to the number of elements in the parameter container.
Similar to TreeMap/TreeSet, PriorityQueue requires that either elements implement the Comparable interface or pass a Comparator:
- For the first two constructor methods and the constructor that accepts Collection parameters, the Comparable interface must be implemented for the elements.
- The third constructor explicitly transmits the Comparator.
- For the last two constructor methods, the parameter container has the comparator () method. PriorityQueue uses the same method as them. If the returned comparator is null, the element must also implement the Comparable interface.
Basic example
Let's look at a basic example:
Queue<Integer> pq = new PriorityQueue<>();pq.offer(10);pq.add(22);pq.addAll(Arrays.asList(new Integer[]{ 11, 12, 34, 2, 7, 4, 15, 12, 8, 6, 19, 13 }));while(pq.peek()!=null){ System.out.print(pq.poll() + " ");}
The code is simple. add elements and delete them one by one from the header. Unlike normal queues, the output is sorted from small to large:
2 4 6 7 8 10 11 12 12 13 15 19 22 34
What if I want it to be from big to small? Pass a Comparator in reverse order and replace the first line of code:
Queue<Integer> pq = new PriorityQueue<>(11, Collections.reverseOrder());
The output will be changed:
34 22 19 15 13 12 12 11 10 8 7 6 4 2
Task queue
Let's take a look at an example. simulate a Task queue and define an internal Task class to represent the Task, as shown below:
static class Task { int priority; String name; public Task(int priority, String name) { this.priority = priority; this.name = name; } public int getPriority() { return priority; } public String getName() { return name; }}
A Task has two instance variables. priority indicates the priority. A greater value indicates the higher the priority. name indicates the Task name.
Task does not implement Comparable. We define a separate static member taskComparator to indicate the comparator, as shown below:
private static Comparator<Task> taskComparator = new Comparator<Task>() { @Override public int compare(Task o1, Task o2) { if(o1.getPriority()>o2.getPriority()){ return -1; }else if(o1.getPriority()<o2.getPriority()){ return 1; } return 0; }};
The following shows the sample code of the task queue:
Queue <Task> tasks = new PriorityQueue <Task> (11, taskComparator); tasks. offer (new Task (20, "Diary"); tasks. offer (new Task (10, "watch TV"); tasks. offer (new Task (100, "write code"); Task task = tasks. poll (); while (task! = Null) {System. out. print ("processing task:" + task. getName () + ", priority:" + task. getPriority () + "\ n"); task = tasks. poll ();}
The code is very simple and I will not explain it. The output tasks are sorted by priority:
Processing Task: write code, priority: 100 processing task: write diary, priority: 20 processing task: watch TV, priority: 10
Implementation Principle
After understanding the usage and features of PriorityQueue, let's look at its specific implementation code, starting from the internal composition.
Internal components
There are the following members:
private transient Object[] queue;private int size = 0;private final Comparator<? super E> comparator;private transient int modCount = 0;
Queue is the array of actually stored elements. Size indicates the number of current elements. Comparator is a comparator and can be null. ModCount records the number of modifications, which was introduced when the first container class ArrayList was introduced.
How to implement various operations and maintain the nature of the heap? Let's look at the code, starting with the basic constructor.
Basic Constructor
The code for several basic constructor methods is:
public PriorityQueue() { this(DEFAULT_INITIAL_CAPACITY, null);}public PriorityQueue(int initialCapacity) { this(initialCapacity, null);}public PriorityQueue(int initialCapacity, Comparator<? super E> comparator) { if (initialCapacity < 1) throw new IllegalArgumentException(); this.queue = new Object[initialCapacity]; this.comparator = comparator;}
The code is simple, that is, the queue and comparator are initialized.
The following describes some operation code, most of the algorithms and diagrams. We have already introduced them in the previous section.
Add element (join)
Code:
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 siftUp(i, e); return true;}
The basic steps of the offer method are as follows:
Two steps are more complex. One is grow and the other is siftUp. Let's take a closer look.
The code of the grow method is:
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);}
If the original length is relatively small, it is about two times the extension; otherwise, it is increased by 50%. Use the Arrays. copyOf method to copy the array.
The basic idea of siftUp is described in the previous section. The actual code is as follows:
private void siftUp(int k, E x) { if (comparator != null) siftUpUsingComparator(k, x); else siftUpComparable(k, x);}
Based on whether comparator exists in two cases, the code is similar, we only look at one:
private void siftUpUsingComparator(int k, E x) { while (k > 0) { int parent = (k - 1) >>> 1; Object e = queue[parent]; if (comparator.compare(x, (E) e) >= 0) break; queue[k] = e; k = parent; } queue[k] = x;}
The k parameter indicates the insert position, and x indicates the new element. K is equal to the size of the array, that is, insert at the last position. The main part of the code is to look up the position where x really should be inserted, which is represented by k.
How to find it? The new element (x) is constantly compared with the parent node (e). If the new element (x) is greater than or equal to the parent node (e), the heap is satisfied and the loop is exited, k is the final position of the new element. Otherwise, move the parent node down (queue [k] = e) and continue searching for it. This corresponds to the algorithms and diagrams described in the previous section.
View header Elements
Code:
public E peek() { if (size == 0) return null; return (E) queue[0];}
Returns the first element.
Delete header elements (Team)
Code:
public E poll() { if (size == 0) return null; int s = --size; modCount++; E result = (E) queue[0]; E x = (E) queue[s]; queue[s] = null; if (s != 0) siftDown(0, x); return result;}
The returned result is the first element. x points to the last element and sets the last position to null (queue [s] = null ), finally, call siftDown to insert the original final element x into the header and adjust the heap. The Code of siftDown is:
private void siftDown(int k, E x) { if (comparator != null) siftDownUsingComparator(k, x); else siftDownComparable(k, x);}
The code is similar to the following two cases:
private void siftDownComparable(int k, E x) { Comparable<? super E> key = (Comparable<? super E>)x; int half = size >>> 1; // loop while a non-leaf while (k < half) { int child = (k << 1) + 1; // assume left child is least Object c = queue[child]; int right = child + 1; if (right < size && ((Comparable<? super E>) c).compareTo((E) queue[right]) > 0) c = queue[child = right]; if (key.compareTo((E) c) <= 0) break; queue[k] = c; k = child; } queue[k] = key;}
K indicates the final insert position. The initial value is 0, and x indicates the original last element. The main part of the code is to look down at the position where x really should be inserted, which is represented by k.
How to find it? The new element key is constantly compared with a small child. If it is smaller than or equal to a small child, the heap is satisfied. Exit the loop and k is the final position, otherwise, move the child up and search for the child. This corresponds to the algorithms and diagrams introduced in the previous section.
Explain some of the code below:
- K
- Child indicates a small child number. Initially, it is a left child. If there is a right child (number right) and less than the left child, the child will change to right.
- C Indicates a small child node.
Search Element
Code:
public boolean contains(Object o) { return indexOf(o) != -1;}
The Code of indexOf is:
private int indexOf(Object o) { if (o != null) { for (int i = 0; i < size; i++) if (o.equals(queue[i])) return i; } return -1;}
The code is simple, that is, the search of arrays..
Delete element by value
You can also delete the element based on the value. The code is:
public boolean remove(Object o) { int i = indexOf(o); if (i == -1) return false; else { removeAt(i); return true; }}
First look for the position I of the element, and then call removeAt to delete it. The removeAt code is:
private E removeAt(int i) { assert i >= 0 && i < size; modCount++; int s = --size; if (s == i) // removed last element queue[i] = null; else { E moved = (E) queue[s]; queue[s] = null; siftDown(i, moved); if (queue[i] == moved) { siftUp(i, moved); if (queue[i] != moved) return moved; } } return null;}
If the last position is deleted, delete it directly. Otherwise, move the last element to position I and adjust the heap. There are two ways to adjust it. If it is greater than the child node, adjust it downward, otherwise, it is adjusted up if it is smaller than the parent node.
The code first adjusts down (siftDown (I, moved). If it has not been adjusted (queue [I] = moved), it may need to adjust up and call siftUp (I, moved ).
If it is adjusted up, the return value is moved. Otherwise, null is returned. This is mainly used to correctly implement the delete method of the PriorityQueue iterator. We will not introduce the details of the iterator.
Build the initial heap
If you construct a heap from a container that is neither PriorityQueue nor SortedSet, the code is:
private void initFromCollection(Collection<? extends E> c) { initElementsFromCollection(c); heapify();}
The main code of initElementsFromCollection is:
private void initElementsFromCollection(Collection<? extends E> c) { Object[] a = c.toArray(); if (a.getClass() != Object[].class) a = Arrays.copyOf(a, a.length, Object[].class); this.queue = a; this.size = a.length;}
It mainly initializes queue and size.
The heapify code is:
private void heapify() { for (int i = (size >>> 1) - 1; i >= 0; i--) siftDown(i, (E) queue[i]);}
Like the previous algorithms, heapify has also been introduced in the previous section, that is, starting from the last non-leaf node, the heap is merged from the bottom up to build the heap.
If the parameters in the constructor are PriorityQueue or SortedSet, the arrays returned by their toArray method are ordered, which satisfies the heap nature and does not require heapify.
PriorityQueue features
PriorityQueue implements the Queue interface, which has a priority and is implemented using a heap internally. This determines that it has the following features:
- The priority queue is implemented. The first queue always has the highest priority, that is, the first queue in the sorting.
- The priorities can be the same. The internal elements are not completely ordered. If the output is traversed, there is no specific order except the first one.
- It is very efficient to view the header elements. For example, for O (1), it is more efficient to join and leave the queue. For O (log2 (N), the efficiency of building heapify for heapify is O (N ).
- The efficiency of searching and deleting elements by value is relatively low, which is O (N ).
Summary
This section describes the Java heap implementation class PriorityQueue, which implements the Queue interface Queue, but queues by priority. We introduce the method and implementation code.
In addition to being used as a basic priority queue, PriorityQueue can also be used as a common data structure to solve some other problems. Let's continue to explore in the next section.
---------------
For more information, see the latest article. Please pay attention to the Public Account "lauma says programming" (scan the QR code below), from entry to advanced, ma and you explore the essence of Java programming and computer technology. Retain All copyrights with original intent.