2013-11-25 20 views
-1

我打算使用的PriorityQueue作爲最小堆了5個元素,每個元素都被聲明爲以下一個元組:爲什麼我的Java的PriorityQueue的行爲奇怪

public class Tuple implements Comparator<Tuple> { 
    public final int x; 
    public final double y; 

    public Tuple(int x, double y) { 
     this.x = x; 
     this.y = y; 
    } 

    public Tuple() { 
     this.x = 0; 
     this.y = 0; 
    } 

    @Override 
    public int compare(Tuple o1, Tuple o2) { 
     return (int) (o1.y - o2.y); 
    } 
} 

然後,我宣佈我堆中

PriorityQueue<Tuple> heap = new PriorityQueue<Tuple>(5, new Tuple()); 
int capacity = 5; 

然後,我用下面的代碼添加元素:

其中
if (capacity != 0) { 
      if (score > 0) { 
       Tuple tmp = new Tuple(i, score); 
       heap.add(tmp); 
       capacity -= 1; 
      } 
     } else { 
      if (score > heap.peek().y) { 
       OutPutPriorityQueue(heap); 
       Tuple tmp = new Tuple(i, score); 
       heap.remove(); 
       heap.add(tmp); 
       OutPutPriorityQueue(heap); 
      } 
     } 

scoredouble別處計算OutPutPriorityQueue聲明如下:

public void OutPutPriorityQueue(PriorityQueue<Tuple> heap){ 
    Tuple [] temp = new Tuple[5]; 
    for (int i=0;i<5;i++){ 
     temp[i] = heap.poll(); 
     System.out.print(temp[i].y+"\t"); 
    } 
    System.out.println(); 
    for (int i=0; i<5; i++){ 
     heap.add(temp[i]); 
    } 
} 

對不起,我列出了太多的代碼在這裏,但是這是我第一次使用PriorityQueue的,我不知道哪裏出了問題和代碼的邏輯應該很簡單。

然後我的問題是,我的功能OutPutPriorityQueue,這是應該根據爲了打印元件,打印在基本上任意方式的元件的輸出,這裏是一些示例:

0.5549890273805606 0.6479515952918626 0.8593378488473195 0.53232731034541 1.0 
1.0 0.8593378488473195 0.53232731034541 0.8593378488473195 0.6479515952918626 
1.0 0.6479515952918626 0.8593378488473195 0.53232731034541 0.8593378488473195 
0.8593378488473195 1.6093378488473196 0.53232731034541 0.8593378488473195 0.6479515952918626 
0.8593378488473195 0.6479515952918626 0.8593378488473195 0.53232731034541 1.6093378488473196 
1.6093378488473196 1.28601715282334 0.53232731034541 0.8593378488473195 0.6479515952918626 

這些數字很​​難看,但它的行爲可以概括爲以下幾點:

  1. remove()add()去除頭一個,將第5一個頭,並插入在第二位的一個新的。
  2. 2n-1應該與行2n完全一樣,但它們是不同的。注:第二個(最新的)被換與第五一個
  3. 似乎沒有在此隊列中定義的順序,但我定義了一個compare(),並通過它英寸

我不知道爲什麼這個正在發生,我希望有人能幫助我。
我正確使用compare()嗎?或者是其他東西?

非常感謝!

+0

閱讀[二元堆](http://en.wikipedia.org/wiki/Binary_heap),這就是'PriorityQueue'的實現方式。 –

+0

謝謝@SotiriosDelimanolis,但這隻會讓我的堆表現得更加奇怪,不是嗎? –

+0

你能發佈一個完整的工作示例,以便我可以準確地再現你需要解釋的內容嗎? –

回答

1

沒有深入你隊列的細節我會做的第一件事就是改變比較器。遠離演員陣營並使用Double提供的比較器。

public static int compare(double d1, double d2) 

從API返回 - 如果d1在數字上等於d2,則值爲0;如果d1在數字上小於d2,則該值小於0;如果d1在數值上大於d2,則值大於0。

比較你有錯誤傾向於投注可能會導致你的問題。

+0

謝謝。這是一個很好的結果,但我有兩點,(1)。當我使用'LinkedList '並使用'Collections.sort()'時,'compare'可以正常工作。但是,我仍然想嘗試你的解決方案,(2)。但遺憾的是,我不知道如何在我的覆蓋'compare'中使用'static'函數。我改變不了我的'compare'到'static'也不初始化'Comparator' :-( –

+0

我明白了,你會做以下幾點: \t'@覆蓋 \t公衆詮釋比較(數組O1,O2元組) { \t \t回Double.compare(o1.y,o2.y); \t}' – TechTrip

+0

謝謝你的好意,可惜......代碼的行爲基本上是相同的...... :-( –