標籤:
優先順序隊列,顧名思義,和傳統“先進後出”的隊列相比,優先順序隊列在元素加入時就根據該元素的優先順序插入到相應位置。實際上優先順序隊列PriotyQueue在poll時還是遵循先進後出,只是資料在進入時已經根據優先順序排序了。實現優先順序隊列需要實現一個Comparator,測試代碼如下:
public class PriotyQueueTest {
//比較子,用於判斷兩個元素的優先順序 Comparator<Man> t = new Comparator<Man>() { @Override public int compare(Man o1, Man o2) { if(o1.getAge() == o2.getAge()) return 0; if(o1.getAge() > o2.getAge()) return 1; return -1; } }; Queue<Man> queue = new PriorityQueue<Man>(11,t);
//將給定數組添加到優先順序隊列中 public void add(int[] nums){ for(int i = 0 ; i < nums.length ; i++) queue.add(new Man(String.valueOf(i),nums[i])); }
//列印函數 public void print(){ while(queue.peek()!=null){ System.out.println(queue.poll().getAge()+" "); } System.out.println(); } public static void main(String[] args) { int[] test = new int[]{5,4,2,3,1}; PriotyQueueTest q = new PriotyQueueTest(); q.add(test); q.print(); }}
//測試實體類class Man{ private String name; private int age; public Man(String name,int age){ this.name = name; this.age = age; } public String getName() { return name; } public void setName(String name) { this.name = name; } public int getAge() { return age; } public void setAge(int age) { this.age = age; }} 讓我好奇的是,這裡的add( )函數中究竟發生了什嗎?我們把這部分原始碼拿出來review一下:
private void siftUpUsingComparator(int k, E x) { while (k > 0) { int parent = (k - 1) >>> 1;<span style="white-space:pre"></span>//下標右移一位,相當於除2 Object e = queue[parent];<span style="white-space:pre"></span>//得到父節點 if (comparator.compare(x, (E) e) >= 0)<span style="white-space:pre"></span>//比較,如果優先順序大於父節點則停止向上搜尋 break; queue[k] = e; k = parent; } queue[k] = x; } 從上面的代碼我們可以看到:
1、Queue是基於對象數組實現的,並抽象成樹結構;
2、這裡的比較子的含義是:直到優先順序小於待插元素時停止搜尋;
3、刪除的時間複雜度為O(1),插入的時間複雜度為O(n)
Java優先順序隊列PriotyQueue