How to implement binary search algorithm in Lua

1 Answer

0 votes
function binarySearch(arr, value)
    local low = 1
    local high = #arr
 
    while low <= high do
        local mid = math.floor((low + high) / 2)
        if arr[mid] > value then high = mid - 1
            elseif arr[mid] < value then low = mid + 1
                else return mid
        end
    end

    return false
end
 
arr = {2, 3, 4, 7, 9, 12, 14, 15, 18, 22}
 
print(binarySearch(arr, 9))
 
 
 
 
--[[
run:
 
5
 
 --]]

 



answered Dec 22, 2022 by avibootz
edited Dec 22, 2022 by avibootz

Related questions

1 answer 15 views
15 views asked May 19 by avibootz
2 answers 101 views
1 answer 101 views
101 views asked Feb 15, 2023 by avibootz
1 answer 92 views
92 views asked Feb 15, 2023 by avibootz
...