【发布时间】:2012-05-22 20:04:04
【问题描述】:
我正在研究一种 c++ 快速排序算法,该算法计算排序期间重要操作的数量。它会正确排序 100 个值,但之后会陷入无限循环。任何帮助将不胜感激!
//快速排序.cpp
#include "QuickSort.h"
#include <algorithm>
using namespace std;
QuickSort::QuickSort(int max) : SortData(max)
{
/*
maxSize = max;
theData = new long[max];
*/
SortData::randomize(12);
}
QuickSort::~QuickSort(void)
{
}
_int64 QuickSort:: sort()
{
numops = 0;
quicksort(theData, 0, (size()-1));
return(numops);
}
//Include counting number of operations
void QuickSort::quicksort(long theData[], int left, int right)
{
//Default variables
if (size() <= 1 || left >= size() || right >= size()) return; //Bounds checking
if (left < right)
{
long pivot = partition(theData, left, right);
quicksort(theData, left, pivot-1);
quicksort(theData, pivot+1, right);
}
}
int QuickSort::partition(long theData[], int left, int right)
{
long pivot = theData[left];
while (true)
{
while (theData[left] < pivot) left++;
numops ++;
while (theData[right] > pivot) right--;
numops ++;
if (left < right)
{
swap(theData[left], theData[right]);
numops+=3;
}
else
{
return right;
}
}
}
//快速排序.h
#pragma once
#include "SortData.h"
class QuickSort : public SortData
{
public:
QuickSort(int max = 100);
~QuickSort(void);
_int64 sort();
private:
_int64 numops;
void QuickSort::quicksort(long theData[], int left, int right);
int partition(long theData[], int left, int right);
};
【问题讨论】:
-
SortData 是什么样的?它实际上是在构造函数中分配一个最大大小的数组吗?
-
您的
partition函数看起来如果找到两个等于枢轴的元素,它将进入无限循环(我可能弄错了,没有仔细研究您的代码)。如果这不是家庭作业,请使用std::partition。 -
另请注意,您的
numops跳过了很多分区逻辑。 -
这里是 sortdata 的要点gist.github.com/2771303
-
numops 应该只计算排序中重要操作的数量。
标签: c++ algorithm sorting quicksort