我正在研究一種C++ quicksort算法,它可以計算排序過程中重要操作的數量。它會正確地對100個值進行排序,但之後會陷入無限循環。任何幫助將不勝感激!C++ Quicksort Algorithm Crashing
//QuickSort.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;
}
}
}
//QuickSort.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是什麼樣的?它實際上是在構造函數中分配一個max max數組嗎? – emsr
你的'分區'函數看起來好像會進入一個無限循環,如果它發現兩個元素等於主鍵(我可能會誤解,沒有仔細研究你的代碼)。如果這不是作業,只需使用'std :: partition'。 –
另請注意,你的'numops'跳過了很多parition邏輯。 –