计算在Heapsort中完成的比较次数

时间:2017-03-24 09:25:04

标签: c++ sorting heap priority-queue

我正在尝试计算堆排序算法完成的比较次数。 我的代码基于优先级队列,我想知道我应该把计数器放在哪里。这是我所拥有的,但是当我尝试打印计数器时,它显示零计数,我做错了什么?谢谢。

这是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;

}

2 个答案:

答案 0 :(得分:0)

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();
   }

答案 1 :(得分:0)

您希望在进行比较之前递增计数器。从您的shiftRight方法中考虑此代码:

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

}

如果条件为真,则仅递增计数器。如果pq_keys[swpIdx] >= pq_keys[leftChild],那么您进行了比较而不计算它。您需要将代码更改为:

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

}

你需要在计算比较的其他两个地方做同样的事情:增加计数器,然后进行比较。