查找最后一位小于等于 value 的元素(从中位数查找,节约大量性能)

-- 查找最后一位小于等于value的元素
-- 有序数组 从小到大
-- @param t 待搜索table
-- @param filter_func 刷选器,支持数组元素可以为table
-- @param value 搜索值
-- @return index 返回位置下标 -1没找到
function BinaryUtils:bindSearchLastLessOrEqual(t, value, filter_func)
    local low = 1
    local high = #t

    local higt_value = filter_func and filter_func(t[high]) or t[high]
    local low_value = filter_func and filter_func(t[low]) or t[low]
    if not higt_value then
        return -1
    end

    if not low_value then
        return -1
    end

    if higt_value <= value then
        return high + 1
    end
    if low_value >= value then
        return low
    end

    while low <= high do
        local mid = low + math.floor((high - low) / 2)
        local mid_value = filter_func and filter_func(t[mid]) or t[mid]
        if not mid_value then
            return -1
        end
        if mid_value > value then
            high = mid - 1
        else
            local filter_value = filter_func and filter_func(t[mid + 1]) or t[mid + 1]
            if mid == high or filter_value > value then
                return mid
            else
                low = mid + 1
            end
        end
    end
    return -1
end

 如在 {1,222,33,4,55,61,7,86,19,...100000} 中,找到 小于等于 10000 的所有元素中,的最后一位

使用案例: 

  conf:{index:number,num:number}[]

  

  

  这样就可以通过对比当前排名 2 ,去拿到 num中,所有小于 2 的 集合 {1,2}  中的 2

原文地址:https://www.cnblogs.com/dmc-nero/p/14462337.html