Skip to content

Instantly share code, notes, and snippets.

@echohes
Created February 13, 2022 22:16
Show Gist options
  • Save echohes/81bc839c175c092d440c839926373332 to your computer and use it in GitHub Desktop.
Save echohes/81bc839c175c092d440c839926373332 to your computer and use it in GitHub Desktop.
binary search in Lua
l={}
for i=1,1000000 do
table.insert(l,i)
end
function b(t,i)
max=#t
low=1
while low<=max do
mid=math.ceil((max+low)/2)
print("find:",max,low,mid)
if t[mid]==i then
return mid
end
if t[mid]>i then
max = mid-1
else
low = mid+1
end
end
return "Not"
end
print(b(l,1))
print(b(l,1000000))
print(b(l,499999))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment