Priority queue
Thanks Modifying Code in Columbia crush on a data structure , the classic of classics.
Thanks Modifying Code in Columbia crush on a data structure , the classic of classics.
Thanks Modifying Code in Columbia crush on a data structure , the classic of classics.
Priority queue Profile
Priority queue is a queue , and therefore provides the following interfaces
public interface Queue<E> {
int size(); // 元素的数量
boolean isEmpty(); // 是否为空
void enQueue(E element); // 入队
E deQueue(); // 出队
E front(); // 获取队列的头元素
void clear(); // 清空
}
Queue with priority queue:
- Common queue is FIFO principle, which is the first in first out
- Priority queue is in accordance with the priority level of conduct from the team,
such as the highest priority elements as the team heads priority from the team.
Priority queue scenarios:
- Night hospital outpatient
queue element is patient
priority is serious cases of illness, registration time - Multi-tasking operating system scheduling
queue element is the task
priority task type
Priority underlying queue implementation
- Using the binary heap as a priority queue underlying implementation
- By Comparator or Comparable to customize the level of priority
Binary heap priority queue source code to achieve
Using the binary heap implemented priority queue.
/**
* 二叉堆实现优先级队列
* @author yusael
*/
public class PriorityQueue<E> {
private BinaryHeap<E> heap;
// 通过 comparator 自定义优先级高低
public PriorityQueue(Comparator<E> comparator) {
heap = new BinaryHeap<>(comparator);
}
public PriorityQueue() {
this(null);
}
public int size() {
return heap.size();
}
public boolean isEmpty() {
return heap.isEmpty();
}
public void clear() {
heap.clear();
}
public void enQueue(E element) {
heap.add(element);
}
public E deQueue() {
return heap.remove();
}
public E front() {
return heap.get();
}
}
Test code
Person.java
public class Person implements Comparable<Person> {
private String name;
private int boneBreak;
public Person(String name, int boneBreak) {
this.name = name;
this.boneBreak = boneBreak;
}
@Override
public int compareTo(Person person) {
return this.boneBreak - person.boneBreak;
}
@Override
public String toString() {
return "Person [name=" + name + ", boneBreak=" + boneBreak + "]";
}
}
Main.java
public class Main {
public static void main(String[] args) {
PriorityQueue<Person> queue = new PriorityQueue<>();
queue.enQueue(new Person("Jack", 2));
queue.enQueue(new Person("Rose", 10));
queue.enQueue(new Person("Jake", 5));
queue.enQueue(new Person("James", 15));
while (!queue.isEmpty()) {
System.out.println(queue.deQueue());
}
}
}
Person [name=James, boneBreak=15]
Person [name=Rose, boneBreak=10]
Person [name=Jake, boneBreak=5]
Person [name=Jack, boneBreak=2]