Priority Queue Implementation

In Java, the PriorityQueue class is implemented as a priority heap. Heap is an important data structure in computer science. For a quick overview of heap, here is a very good tutorial.

1. Simple Example

The following examples shows the basic operations of PriorityQueue such as offer(), peek(), poll(), and size().

import java.util.Comparator;
import java.util.PriorityQueue;
 
public class PriorityQueueTest {
 
    static class PQsort implements Comparator<Integer> {
 
        public int compare(Integer one, Integer two) {
            return two - one;
        }
    }
 
    public static void main(String[] args) {
        int[] ia = { 1, 10, 5, 3, 4, 7, 6, 9, 8 };
        PriorityQueue<Integer> pq1 = new PriorityQueue<Integer>();
 
        // use offer() method to add elements to the PriorityQueue pq1
        for (int x : ia) {
            pq1.offer(x);
        }
 
        System.out.println("pq1: " + pq1);
 
        PQsort pqs = new PQsort();
        PriorityQueue<Integer> pq2 = new PriorityQueue<Integer>(10, pqs);
        // In this particular case, we can simply use Collections.reverseOrder()
        // instead of self-defined comparator
        for (int x : ia) {
            pq2.offer(x);
        }
 
        System.out.println("pq2: " + pq2);
 
        // print size
        System.out.println("size: " + pq2.size());
        // return highest priority element in the queue without removing it
        System.out.println("peek: " + pq2.peek());
        // print size
        System.out.println("size: " + pq2.size());
        // return highest priority element and removes it from the queue
        System.out.println("poll: " + pq2.poll());
        // print size
        System.out.println("size: " + pq2.size());
 
        System.out.print("pq2: " + pq2);
 
    }
}

Output:

pq1: [1, 3, 5, 8, 4, 7, 6, 10, 9]
pq2: [10, 9, 7, 8, 3, 5, 6, 1, 4]
size: 9
peek: 10
size: 9
poll: 10
size: 8
pq2: [9, 8, 7, 4, 3, 5, 6, 1]

2. Example of Solving Problems Using PriorityQueue

 

Nearest points on a plane:

http://www.cnblogs.com/hygeia/p/5154490.html

 

Merge K sorted lists:

http://www.cnblogs.com/hygeia/p/5062768.html

 

3. Collections.sort也用到了这个comparator:

Insert Interval:

http://www.cnblogs.com/hygeia/p/5112649.html

转载于:https://www.cnblogs.com/hygeia/p/5159158.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值