Java 的 PriorityQueue 与最小堆有何不同?

发布于 2024-11-08 17:32:25 字数 139 浏览 7 评论 0原文

如果您不能insertWithPriority,为什么他们要命名PriorityQueue?它看起来与堆非常相似。有什么区别吗?如果没有区别,那么为什么它被命名为PriorityQueue而不是Heap?

Why did they name PriorityQueue if you can't insertWithPriority? It seems very similar to a heap. Are there any differences? If no difference, then why was it named PriorityQueue and not Heap?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(7

过度放纵 2024-11-15 17:32:25

默认的PriorityQueue是用Min-Heap实现的,即栈顶元素是堆中最小的元素。

为了实现最大堆,您可以创建自己的比较器:

import java.util.Comparator;

public class MyComparator implements Comparator<Integer>
{
    public int compare( Integer x, Integer y )
    {
        return y - x;
    }
}

因此,您可以通过以下方式创建最小堆和最大堆:

PriorityQueue minHeap=new PriorityQueue();
PriorityQueue maxHeap=new PriorityQueue(size, new MyComparator());

The default PriorityQueue is implemented with Min-Heap, that is the top element is the minimum one in the heap.

In order to implement a max-heap, you can create your own Comparator:

import java.util.Comparator;

public class MyComparator implements Comparator<Integer>
{
    public int compare( Integer x, Integer y )
    {
        return y - x;
    }
}

So, you can create a min-heap and max-heap in the following way:

PriorityQueue minHeap=new PriorityQueue();
PriorityQueue maxHeap=new PriorityQueue(size, new MyComparator());
迷爱 2024-11-15 17:32:25

对于最大堆,您可以使用:

PriorityQueue<Integer> queue = new PriorityQueue<>(10, Collections.reverseOrder());

For max-heap you can use:

PriorityQueue<Integer> queue = new PriorityQueue<>(10, Collections.reverseOrder());
半世蒼涼 2024-11-15 17:32:25

Add() 的工作方式类似于 insertWithPriority。

您可以使用构造函数定义所需类型的优先级:

PriorityQueue(int, java.util.Comparator)

查看 https://docs.oracle.com/en/java/javase/11/docs/api/java.base/java/util/PriorityQueue.html

比较器给出的顺序将代表队列中的优先级。

Add() works like an insertWithPriority.

You can define priority for the type that you want using the constructor:

PriorityQueue(int, java.util.Comparator)

look under https://docs.oracle.com/en/java/javase/11/docs/api/java.base/java/util/PriorityQueue.html

The order the Comparator gives will represent the priority in the queue.

凯凯我们等你回来 2024-11-15 17:32:25

其他答案中描述的默认行为

最小堆(默认):

PriorityQueue<Integer> priorityQueue = new PriorityQueue<>();

对于最大堆:

PriorityQueue<Integer> priorityQueue = new PriorityQueue<>((o1, o2) -> o2-o1);

Default behaviour as described in other answers

Min Heap(Default):

PriorityQueue<Integer> priorityQueue = new PriorityQueue<>();

For Max Heap:

PriorityQueue<Integer> priorityQueue = new PriorityQueue<>((o1, o2) -> o2-o1);
-黛色若梦 2024-11-15 17:32:25

来自 Java 文档

优先级队列表示为平衡二叉堆:queue[n] 的两个子级是queue[2*n+1] 和queue[2*(n+1)]。优先级队列按比较器排序,或按元素的自然排序排序。


这是使用 PriorityQueuema​​xHeapminHeap 的工作代码 -

class HeapDemo {
    private final static int HEAP_SIZE = 10; //size of heap

    //INNER CLASS
    static class maxHeapComparator implements Comparator<Integer> {
        @Override
        public int compare (Integer x, Integer y) {
            return y-x; //reverse order
        }
    }

    public static void main(String[] args) {
        PriorityQueue<Integer> minHeap = new PriorityQueue<>(HeapDemo.HEAP_SIZE); 
        PriorityQueue<Integer> maxHeap = new PriorityQueue<>(HeapDemo.HEAP_SIZE, new maxHeapComparator());  

        for(int i=1; i<=HeapDemo.HEAP_SIZE; ++i){
            int data = new Random().nextInt(100) +1; //number between 0 to 100
            minHeap.add(data);
            maxHeap.add(data);
        }

        System.out.print("\nMIN Heap : ");
        Iterator<Integer> iter = minHeap.iterator();
        while(iter.hasNext()){
            System.out.print(iter.next() + " ");
        }

        System.out.print("\nMAX Heap : ");
        iter = maxHeap.iterator();
        while(iter.hasNext()) {
            System.out.print(iter.next() + " ");
        }
    }
}

示例 o/p :

MIN Heap : 20 32 37 41 53 91 41 98 47 86 
MAX Heap : 98 91 41 53 86 20 37 41 32 47 

From Java docs

Priority queue represented as a balanced binary heap: the two children of queue[n] are queue[2*n+1] and queue[2*(n+1)]. The priority queue is ordered by comparator, or by the elements' natural ordering.


Here is a working code for maxHeap and minHeap using PriorityQueue -

class HeapDemo {
    private final static int HEAP_SIZE = 10; //size of heap

    //INNER CLASS
    static class maxHeapComparator implements Comparator<Integer> {
        @Override
        public int compare (Integer x, Integer y) {
            return y-x; //reverse order
        }
    }

    public static void main(String[] args) {
        PriorityQueue<Integer> minHeap = new PriorityQueue<>(HeapDemo.HEAP_SIZE); 
        PriorityQueue<Integer> maxHeap = new PriorityQueue<>(HeapDemo.HEAP_SIZE, new maxHeapComparator());  

        for(int i=1; i<=HeapDemo.HEAP_SIZE; ++i){
            int data = new Random().nextInt(100) +1; //number between 0 to 100
            minHeap.add(data);
            maxHeap.add(data);
        }

        System.out.print("\nMIN Heap : ");
        Iterator<Integer> iter = minHeap.iterator();
        while(iter.hasNext()){
            System.out.print(iter.next() + " ");
        }

        System.out.print("\nMAX Heap : ");
        iter = maxHeap.iterator();
        while(iter.hasNext()) {
            System.out.print(iter.next() + " ");
        }
    }
}

sample o/p :

MIN Heap : 20 32 37 41 53 91 41 98 47 86 
MAX Heap : 98 91 41 53 86 20 37 41 32 47 
别把无礼当个性 2024-11-15 17:32:25

来自 PriorityQueue JavaDocs< /a>:

基于优先级堆的无界优先级队列。优先级队列的元素根据其自然顺序进行排序,或者通过队列构造时提供的 Comparator 进行排序,具体取决于使用的构造函数。

优先级是队列中对象的固有属性。元素根据某种比较进行排序。要插入具有给定优先级的某个对象,您只需设置对象上影响排序的任何字段,并且 add() 它。


并且,正如 @Daniel 评论的那样,

一般来说,Java 对象是根据它们提供的功能来命名的,而不是根据它们的实现方式来命名。

From the PriorityQueue JavaDocs:

An unbounded priority queue based on a priority heap. The elements of the priority queue are ordered according to their natural ordering, or by a Comparator provided at queue construction time, depending on which constructor is used.

Priority is meant to be an inherent property of the objects in the queue. The elements are ordered based on some sort of comparison. To insert some object with a given priority, you would just set whatever field(s) on the object affect the ordering, and add() it.


And, as @Daniel commented,

Generally Java Objects are named based on the functionality they provide, not named based on how they are implemented.

滿滿的愛 2024-11-15 17:32:25

来自 http://docs.oracle.com/javase /7/docs/api/java/util/PriorityQueue.html

基于优先级堆的无界优先级队列。优先级队列的元素按照其自然顺序排序,或者按照队列构建时提供的比较器排序

为整数、长整型、浮点型、双精度型、字符型、布尔型提供的比较器进行排序(即原始数据类型)自然排序是升序,这就是为什么 Arrays.sort(arr) {其中 arr 是原始数据类型的数组}按升序对 arr 的值进行排序。您可以使用比较器更改自然顺序

比较器可以通过两种方式使用

  • 其中一种方式是DpGeek 展示了

  • 另一种方法是使用匿名类。例如

Arrays.sort(arr, new Comparator<Integer>() {
     public int compare(Integer x, Integer y) {
         return y - x;
     }
});
  • 如果您有 java8,则可以使用 lambda 表达式

Arrays.sort(arr, (Integer x, Integer y) -> y - x);

这会按降序对数组 arr 进行排序

From http://docs.oracle.com/javase/7/docs/api/java/util/PriorityQueue.html

An unbounded priority queue based on a priority heap. The elements of the priority queue are ordered according to their natural ordering, or by a Comparator provided at queue construction time

for integer, long, float, double, character, boolean (i.e. primitive data types) the natural ordering is ascending order, that's why Arrays.sort(arr) {where arr is an array of primitive data type} sorts the value of arr in ascending order. You can change the natural ordering by using a Comparator

Comparator can be used in two ways either

Arrays.sort(arr, new Comparator<Integer>() {
     public int compare(Integer x, Integer y) {
         return y - x;
     }
});
  • If you have java8 then you can use the lambda expression

Arrays.sort(arr, (Integer x, Integer y) -> y - x);

This sorts the array arr in descending order

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文