在快速排序中计算比较

Counting comparisons in quicksort

本文关键字:比较 计算 快速排序      更新时间:2023-10-16

我正在尝试计算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;
}

您还可以使用带有比较器的任意容器的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是否是一个快速排序。

您可以简单地改进快速排序,它使用任意的函子进行比较并统计一些统计信息。

在HP/Microsoft的std::sort的情况下,如果处于调试模式,则需要进行两次额外的比较,以检查比较是否为"<"而不是"<="。它通过检查<b、 则b<a.如果您是在调试模式下构建的,请尝试在发布模式下构建,看看是否有帮助。