Before starting, I just want to say that I've spent the last 2 hours or so reading SO post about "Quicksort" and "stack overflow", so I'm not just asking randomly, I literally don't know what to do anymore...
Ok, I have to implement a quick sort algorithm and for some reason I couldn't find, I keep getting stack overflow errors. I'm using VS2010, so I've debugged it from beginning to end.
So, here's my code:
const int THRESHOLD = 1;
std::vector<int> data = *new std::vector<int>();
void GetPivotPoint( bool first, int leftBound, int rightBound, int& pivotID )
{
if( first ) // We are choosing the first element as a pivot
{
pivotID = 0;
return;
}
else // We are choosing the median between 1, n/2 and n for our pivot
{
int left = leftBound;
int right = rightBound;
int center = ( left + right ) / 2;
if( data[center] - data[left] < 0 ) data_manip::Swap( data, left, center );
if( data[right] - data[left] < 0 ) data_manip::Swap( data, left, right );
if( data[right] - data[center] < 0 ) data_manip::Swap( data, center, right );
data_manip::Swap( data, center, right );
pivotID = right;
}
}
int Partition( int left, int right )
{
int pivotID = 0;
GetPivotPoint( true, left, right, pivotID );
int pivot = data[pivotID];
int i = left - 1;
int j = right + 1;
while( i < j )
{
i++;
while( data[i] < pivot ) i++;
j--;
while( data[j] > pivot ) j--;
if( i < j )
{
data_manip::Swap( data, i, j );
}
}
return j;
}
void Quicksort( int left, int right )
{
if( left + THRESHOLD > right )
{
algo::Bubblesort( data, left, right );
}
else
{
int partitionPoint = Partition( left, right );
Quicksort( left, partitionPoint );
Quicksort( partitionPoint + 1, right );
}
}
and here's the implementation of the Swap() method
inline void Swap( std::vector<int>& data, int p1, int p2 )
{
int temp = data[p1];
data[p1] = data[p2];
data[p2] = temp;
}
I'm using set with over 1k and up to 500K in them. Also, in this particular code, I'm using the option to get the first element as a pivot, now I know that this isn't optimal, but I need to test that option too. If I do use the median-of-three instead of the first element, than I don't get a stack overflow, however, what could be causing it when I do use the first element as pivot.
Tanks for the help
std::sort.vectorjust dostd::vector<int> data;and nothing else. The way you are usingnewis a memory leak and a very odd practice.