Java優先順序隊列PriotyQueue

來源:互聯網
上載者:User

標籤:

優先順序隊列,顧名思義,和傳統“先進後出”的隊列相比,優先順序隊列在元素加入時就根據該元素的優先順序插入到相應位置。實際上優先順序隊列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

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.