[英]Something wrong with my 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);
}
}
}
由於某種原因,這是陷入無限循環,我只是無法弄清楚出了什么問題,或者說是為什么。 有人可以幫我指點這里發生了什么嗎?
要將std::sort
與DataPair
結構一起使用,可以提供自定義比較器。 在C ++ 11中,這可以使用lambda函數完成:
std::sort(points.begin(), points.end(), [](const DataPair& a, const DataPair& b) {
return a.error < b.error;
});
這將按遞增的error
順序對DataPair
排序。
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)
。 常見的實現使用quicksort或introsort。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.