#pragma once #include namespace YSG{ #define LOWER(offset) l_lower(spaces[offset]) #define UPPER(offset) l_upper(spaces[offset]) template int binary_search(double value, T** spaces, int spaceSize, std::function& l_lower, std::function& l_upper) { int startIndex = 0, endIndex = spaceSize - 1; if(startIndex == endIndex) return startIndex; double min = LOWER(startIndex), max = UPPER(endIndex); if(value < min) { //qDebug() << QString("warnning binary_search value:%1 < %2").arg(value).arg(min); return startIndex; } if(value > max) { //qDebug() << QString("warnning binary_search value:%1 > %2").arg(value).arg(max); return endIndex; } while(startIndex != endIndex) { if(startIndex+1 == endIndex) { double mid = (UPPER(startIndex)+LOWER(endIndex))/2.0; if(value < mid) return startIndex; return endIndex; } int m = (startIndex + endIndex)/2; double lower = m!=0 ? (UPPER(m-1)+LOWER(m))/2.0 : min; double upper = m!=spaceSize-1 ? (UPPER(m)+LOWER(m+1))/2.0 : max; //qDebug() << " lower == " << lower << " upper == " << upper << "midIndex == " << m << " value == " << value; //qDebug() << " startIndex == " << startIndex << " endIndex == " << endIndex; if(value < lower) { endIndex = m; } else if(value > upper) { startIndex = m; } else { return m; } } qDebug() << QString("warnning startIndex:%1, endIndex:%2").arg(startIndex).arg(endIndex); return startIndex; } #undef LOWER #undef UPPER static int binary_search(double value, const QVector& data, bool& ok) { if (data.isEmpty()) { ok = false; return -1; // 返回 -1 表示数组为空 } // 判断排序顺序 bool ascendingOrder = data[0] < data[data.size() - 1]; int left = 0; int right = data.size() - 1; // 二分查找 while (left <= right) { int mid = left + (right - left) / 2; if (mid < data.size() - 1) { if (ascendingOrder) { if (data[mid] <= value && data[mid + 1] > value) { ok = true; return mid; } else if (data[mid] < value) { left = mid + 1; } else { right = mid - 1; } } else { // 处理降序排列的情况 if (data[mid] >= value && data[mid + 1] < value) { ok = true; return mid; } else if (data[mid] > value) { left = mid + 1; } else { right = mid - 1; } } } else { break; // 如果 mid 已经是最后一个元素,不再继续查找 } } ok = false; // 如果找不到,则返回 -1,表示 value 不在区间内 return -1; } }