1

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?

4

1 回答 1

3

std::sort与您的DataPair结构一起使用,您可以提供自定义比较器。在 C++11 中,这可以通过 lambda 函数来完成:

std::sort(points.begin(), points.end(), [](const DataPair& a, const DataPair& b) {
  return a.error < b.error;
});

这将按DataPairs 的升序对 s 进行排序error

C++03的做法是提供比较功能:

bool compare(const DataPair& a, const DataPair& b)
{
  return a.error < b.error;
}

std:sort(points.begin(), points.end(), compare);

的复杂度std::sort保证为O(NlogN)。常见的实现使用快速排序或 introsort。

于 2013-02-21T18:10:58.747 回答