Skip to content

Instantly share code, notes, and snippets.

@ZwerOxotnik
Last active September 8, 2022 06:10
Show Gist options
  • Save ZwerOxotnik/a6b91f54182183e1415330584c38d73f to your computer and use it in GitHub Desktop.
Save ZwerOxotnik/a6b91f54182183e1415330584c38d73f to your computer and use it in GitHub Desktop.
Binary search for Lua 5.x
do
local floor = math.floor
---@param tbl any[]
---@param value any
---@param iStart integer?
---@param iEnd integer?
---@param reversed boolean?
---@return any?
function binSearch(tbl, value, iStart, iEnd, reversed)
-- Initialise numbers
iStart, iEnd = iStart or 1, iEnd or #tbl
local iMid = 0
if reversed then
-- Reversed Binary Search
while iStart <= iEnd do
-- calculate middle
iMid = floor( (iStart+iEnd) / 2 )
-- get compare value
local value2 = tbl[iMid]
-- get all values that match
if value == value2 then
return iMid
-- keep searching
elseif value > value2 then
iEnd = iMid - 1
else
iStart = iMid + 1
end
end
else
-- Binary Search
while iStart <= iEnd do
-- calculate middle
iMid = floor( (iStart+iEnd) / 2 )
-- get compare value
local value2 = tbl[iMid]
-- get all values that match
if value == value2 then
return iMid
-- keep searching
elseif value < value2 then
iEnd = iMid - 1
else
iStart = iMid + 1
end
end
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment