Reputation: 3509
I've following code for a quicksort:
typedef struct tagDataPair {
int c_value;
float error;
} DataPair;
void SortByErrorQS(std::vector<DataPair>& points, int left, int right)
{
std::vector<int> stack;
stack.push_back(left);
stack.push_back(right);
while(stack.size() > 0)
{
right = stack.back();
stack.pop_back();
left = stack.back();
stack.pop_back();
float pivot = (points.at(left).error + points.at(right).error + points.at((left + right)>>1).error)/3;
int i = left, j = right;
DataPair temp;
while(i < j)
{
while(points.at(i).error <= pivot && (i <= right))
++i;
while(points.at(j).error > pivot && (j > left))
--j;
if(i <= j)
{
temp = points[i];
points[i] = points[j];
points[j] = temp;
i++; j--;
}
}
if(left < j)
{
stack.push_back(left);
stack.push_back(j);
}
if(i < right)
{
stack.push_back(i);
stack.push_back(right);
}
}
}
For some reason this is stuck in an infinite loop, and I just cannot figure out what is going wrong, or rather why. Can someone help me with a pointer what's happening here?
Upvotes: 1
Views: 91
Reputation: 110658
To use std::sort
with your DataPair
struct, you can provide a custom comparator. In C++11, this can be done with a lambda function:
std::sort(points.begin(), points.end(), [](const DataPair& a, const DataPair& b) {
return a.error < b.error;
});
This will sort the DataPair
s in increasing order of error
.
The C++03 approach is to provide a comparison function:
bool compare(const DataPair& a, const DataPair& b)
{
return a.error < b.error;
}
std:sort(points.begin(), points.end(), compare);
The complexity of std::sort
is guaranteed to be O(NlogN)
. Common implementations use quicksort or introsort.
Upvotes: 3