简体   繁体   English

我的QuickSort有问题

[英]Something wrong with my QuickSort

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? 有人可以帮我指点这里发生了什么吗?

To use std::sort with your DataPair struct, you can provide a custom comparator. 要将std::sortDataPair结构一起使用,可以提供自定义比较器。 In C++11, this can be done with a lambda function: 在C ++ 11中,这可以使用lambda函数完成:

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 . 这将按递增的error顺序对DataPair排序。

The C++03 approach is to provide a comparison function: C ++ 03方法是提供比较函数:

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) . std::sort的复杂性保证为O(NlogN) Common implementations use quicksort or introsort. 常见的实现使用quicksort或introsort。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM