簡體   English   中英

計算在Heapsort中完成的比較次數

[英]Counting the number of comparisons done in Heapsort

我試圖計算通過堆排序算法完成的比較次數。 我的代碼基於優先級隊列,我想知道應該將計數器放在哪里。 這是我所擁有的,但是當我嘗試打印計數器顯示零計數時,我在做什么錯呢? 謝謝。

這是heapbuild函數:

#include<iostream>

vector<int> pq_keys;
void buildHeap()
{
int size = pq_keys.size();
int midIdx = (size -2)/2;
while (midIdx >= 0)
{      
    shiftRight(midIdx, size-1);     
    --midIdx;
}

這是進行比較的功能:

int shiftRight(int low, int high)
{
  int root = low;
  int counter=0;
  while ((root*2)+1 <= high)
    {
      int leftChild = (root * 2) + 1;
      int rightChild = leftChild + 1;
      int swapIdx = root;
      if (pq_keys[swapIdx] < pq_keys[leftChild])
    {
      counter++;
      cout<<counter;
      swapIdx = leftChild;

    }
    /*If right child exists check if it is less than current root*/
    if ((rightChild <= high) && (pq_keys[swapIdx] < pq_keys[rightChild]))
    {
    counter++;
    swapIdx = rightChild;    
    }
    /*Make the biggest element of root, left and right child the root*/
    if (swapIdx != root)
    { 
    counter++;
    int tmp = pq_keys[root];
    pq_keys[root] = pq_keys[swapIdx];
    pq_keys[swapIdx] = tmp;
    root = swapIdx;
    }
    else
    {
        break;
    }
}

return counter;

}
class LessPredicate 
{
  size_t callCount_ = 0;

  temlate<class T> 
  bool compare(const T& l, conct T& r)
  {
     return l < r; // or other logic
  }
public:
  size_t CallTimes() const { return callCount_; }
  temlate<class T> 
  bool operator() (const T& l, conct T& r)
  {
    ++callCount_;
    return compare(l, r);
  }
};



   int main() 
   {
     LessPredicate less;
     ...// use it like less(a, b) instead a < b;
     auto compareCount = less.CallTimes();
   }

您想要在進行比較之前增加計數器。 考慮一下您的shiftRight方法中的以下代碼:

if (pq_keys[swapIdx] < pq_keys[leftChild])
{
  counter++;
  cout<<counter;
  swapIdx = leftChild;

}

僅在條件為true時,計數器才會遞增。 如果pq_keys[swpIdx] >= pq_keys[leftChild] ,則您進行比較時不計算它。 您需要將代碼更改為:

counter++;
if (pq_keys[swapIdx] < pq_keys[leftChild])
{
  cout<<counter;
  swapIdx = leftChild;

}

您需要在對比較進行計數的其他兩個地方做同樣的事情:增加計數器, 然后進行比較。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM