【问题标题】:Counting comparisons in quicksort在快速排序中计算比较
【发布时间】:2014-12-25 07:21:15
【问题描述】:

我正在尝试计算quicksort 的比较次数。对于最坏的情况,它显示 n*n-1/2 比较。因此,对于 8 7 6 5 4 3 2 1 顺序的 8 个输入,它应该是 28 次比较。但是,在我的程序中有 30 个比较。我尝试打印比较,一切都很好,但最后一次比较重复了三次。谁能找到这段代码的错误?

#include<iostream.h>
#include<conio.h>
int ar[10000];
int pivot;
int temp;
int partition(int x, int y);
void quicksort(int f, int l);
int count = 0;
int i;
int index;
void main() {
  clrscr();
  int i;
  for (i = 0; i < 8; ++i) {
    cin >> ar[i];
  }
  quicksort(0, 7);
  cout << "\nThe sum is  " << sum;
  getch();
}
void quicksort(int f, int l) {
  if (f == l)
    return 0;
  if (f < l) {
    pivot = partition(f, l);
    quicksort(f, pivot - 1);
    quicksort(pivot + 1, l);
  }
}
int partition(int f, int l) {
  index = ar[f];
  i = f + 1;
  for (int j = f + 1; j <= l; ++j) {
    if (ar[j] < index) {
      temp = ar[j];
      ar[j] = ar[i];
      ar[i] = temp;
      ++i;
    }
  }
  i = i - 1;
  temp = ar[f];
  ar[f] = ar[i];
  ar[i] = temp;
  return i;
}

【问题讨论】:

  • 似乎对我做了 28 - 见ideone.com/i0XmDA
  • 你的代码没有注释,变量名简洁不清晰,并且充满了全局变量(!);这需要解决。更简洁的代码更容易调试——这是这样做的合理理由。 (另一个是它会让其他程序员更愿意阅读你的代码!)

标签: c++ c quicksort counting


【解决方案1】:

您还可以将任意容器的 STL 排序器与一个简单地计算比较的比较器一起使用。

class LessCompare
{
  public: 
    LessCompare() : m_counter ( 0u ) {}

    template<typename T>
    bool operator() ( T const& lhs, T const& rhs ) const {
      ++m_counter;
       return lhs < rhs;
    }

    unsigned compares() const { return m_counter; }

  private:
   unsigend m_counter;
};

std::vector < T > container;
LessCompare compare;
std::sort ( container.begin(), container.end(), std::ref ( compare ) );
std::cout << "Compares: " << compare.compares() << std::endl;

但是,我很不确定std::sort 是否是快速排序。

您可以简单地改进您的 quicksort,它使用任意 functor 进行比较并计算一些统计信息。

【讨论】:

    【解决方案2】:

    在 HP / Microsoft 的 std::sort 的情况下,如果处于调试模式,则会进行两次额外比较以检查比较是“

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-05-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-07-13
      相关资源
      最近更新 更多