package Pri;
import java.util.Comparator;
import java.util.PriorityQueue;
/**
* @author 真他喵的学不动咯
* @create 2022-08-13--17:12
*/
public class Priority { //小根堆、大根堆
//大根堆
public static class MyComparator implements Comparator<Integer>{
//负数,第一个参数在前
//整数,第二个参数在前
@Override
public int compare(Integer o1, Integer o2) {
if (o1>o2){
return -1;
}
if (o1<o2){
return 1;
}else{
return 0;}
}
}
public static void main(String[] args){
//小根堆,小数在前
PriorityQueue<Integer> heap=new PriorityQueue<>();
heap.add(6);
heap.add(1);
heap.add(8);
heap.add(9);
heap.add(5);
heap.add(7);
System.out.println(heap.peek()); //输出最小值但不弹出
System.out.println("****************************************");
while (!heap.isEmpty()){ //如果堆不是空的,那就全弹完 按顺序从小到大
System.out.println(heap.poll());
}
System.out.println("================");
//大根堆,大数在前
PriorityQueue<Integer> heap1=new PriorityQueue<>(new MyComparator()); //把比较器塞在构造方法中,注意引用格式
heap1.add(6);
heap1.add(1);
heap1.add(8);
heap1.add(9);
heap1.add(5);
heap1.add(7);
System.out.println(heap1.peek()); //输出最小值但不弹出
System.out.println("****************************************");
while (!heap1.isEmpty()){ //如果堆不是空的,那就全弹完 按顺序从小到大
System.out.println(heap1.poll());
}
System.out.println("================");
String t1="eabc";
String t2="d";
System.out.println(t1.compareTo(t2));
}
//有序结构排序
/*
1.PriorityQueue<Show.Student> heap=new PriorityQueue<>(new Show.IdComparator()); //优先队列【实质是堆】
heap.add(s1);
2.TreeSet<Show.Student> treeSet=new TreeSet<>(new Show.IdComparator()); //TreeSet实现有序
*/
}
//小根堆、大根堆
最新推荐文章于 2024-05-31 10:46:10 发布