Welcome to collectivesolver - Programming & Software Q&A with code examples. A website with trusted programming answers. All programs are tested and work.

Contact: aviboots(AT)netvision.net.il

Buy a domain name - Register cheap domain names from $0.99 - Namecheap

Scalable Hosting That Grows With You

Secure & Reliable Web Hosting, Free Domain, Free SSL, 1-Click WordPress Install, Expert 24/7 Support

Semrush - keyword research tool

Boost your online presence with premium web hosting and servers

Disclosure: My content contains affiliate links.

39,971 questions

51,913 answers

573 users

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 112 views
112 views asked May 19, 2025 by avibootz
2 answers 157 views
2 answers 172 views
1 answer 168 views
168 views asked Feb 15, 2023 by avibootz
1 answer 138 views
138 views asked Feb 15, 2023 by avibootz
1 answer 167 views
1 answer 179 views
...