RosettaCodeData/Task/Binary-search/Pluto/binary-search.pluto
2026-04-30 12:34:36 -04:00

34 lines
937 B
Text

require "table2"
local fmt = require "fmt"
local function rec_bsearch(a, v, low = 1, high = #a)
if high < low then return false, 0 end
local mid = low + (high - low) // 2
if a[mid] > v then return rec_bsearch(a, v, low, mid - 1) end
if a[mid] < v then return rec_bsearch(a, v, mid + 1, high) end
return true, mid
end
local a = {10, 22, 45, 67, 89, 97}
fmt.lprint(a, ", ", "{}", "array = ")
print()
local texts = {"Using the library function (iterative algorithm):",
"Using the recursive algorithm:"}
local values = { {22, 70}, {67, 93} }
local fns = {table.bsearch, rec_bsearch}
for i = 1, 2 do
print(texts[i])
for values[i] as v do
local found, index = fns[i](a, v)
if found then
print($" {v} was found at index {index} of the array")
else
print($" {v} was not found in the array")
end
end
if i == 1 then print() end
end