java 按指定值排序对象的优先级队列

d6kp6zgx  于 2023-06-28  发布在  Java
关注(0)|答案(4)|浏览(138)

我想通过使用如下指定值将对象添加到优先级队列

PriorityQueue<Edge> queue=new PriorityQueue<Edge>();

这是我想要在优先级队列中按其权重排序的类Edge

public class Edge {
private int start,end;
private double weight;

public Edge(int s, int e,Double w){
    start=s;
    end=e;
    weight=w;
}

public int getStart(){
    return start;
}

public int getEnd(){
    return end;
}

public double getWeight(){
    return weight;
}
ars1skjm

ars1skjm1#

您应该通过指定如何比较其元素来创建稍微不同的优先级队列。这是通过为Edge类传递一个匿名Comparator来完成的:

PriorityQueue<Edge> queue=new PriorityQueue<Edge>(10, new Comparator<Edge>() {
    public int compare(Edge edge1, Edge edge2) {
        if (edge1.getWeight() < edge2.getWeight()) return -1;
        if (edge1.getWeight() > edge2.getWeight()) return 1;
        return 0;
    }
});

也许你需要根据你的排序顺序来切换-11的返回值。

5n0oy7gb

5n0oy7gb2#

您可以创建一个优先级队列和一个比较边的Checker(自定义)类。就像这样:

class Checker implements Comparator<Edge>
  {
      public int compare(Edge ob1, Edge ob2)
      {
          if (ob1.getWeight() > ob2.getWeight()) return 1;
          else                                   return -1;
      }
  }

 //Declared priority queue
  PriorityQueue<Edge> queue=new PriorityQueue<Edge>(5, new Checker());
yk9xbfzb

yk9xbfzb3#

Java 8:

PriorityQueue<Edge> queue = new PriorityQueue<>((edge1, edge2) -> {
            if (edge1.getWeight() < edge2.getWeight()) {
                return -1;
            }
            if (edge1.getWeight() > edge2.getWeight()) {
                return 1;
            }
            return 0;
});
omqzjyyz

omqzjyyz4#

方案一:

最小堆数:

a -> a.getWeight()

最大堆数:

a -> -a.getWeight()

示例:

PriorityQueue<Edge> PriorityQueue = new PriorityQueue<>(Comparator.comparingDouble(a -> a.getWeight()));
PriorityQueue = new PriorityQueue<>(Comparator.comparingDouble(a -> -a.getWeight()));

方案二:

最小堆数:

Edge::getWeight

最大堆数:

(Edge::getWeight).reversed()

示例:

PriorityQueue<Edge> PriorityQueue = new PriorityQueue<>(Comparator.comparingDouble(Edge::getWeight));
PriorityQueue = new PriorityQueue<>(Comparator.comparingDouble(Edge::getWeight).reversed());

方案三:

最小堆数:

(a, b) -> a.getStart() - b.getStart()
(a, b) -> (int) (a.getWeight() - b.getWeight())

最大堆数:

(a, b) -> b.getStart() - a.getStart()
(a, b) -> (int) (b.getWeight() - a.getWeight())

示例:

PriorityQueue<Edge> PriorityQueue = new PriorityQueue<>((a, b) -> a.getStart() - b.getStart());
PriorityQueue = new PriorityQueue<>((a, b) -> (int) (a.getWeight() - b.getWeight()));
PriorityQueue = new PriorityQueue<>((a, b) -> b.getStart() - a.getStart());
PriorityQueue = new PriorityQueue<>((a, b) -> (int) (b.getWeight() - a.getWeight()));

相关问题