Update 01_binary_search.lua
This commit is contained in:
committed by
Aditya Bhargava
parent
525ff6c314
commit
e3016960ee
@@ -1,10 +1,10 @@
|
|||||||
function binary_search(table, value)
|
function binary_search(array, value)
|
||||||
-- Lua arrays start with 1
|
-- Lua arrays start with 1
|
||||||
local low, high = 1, #table
|
local low, high = 1, #array
|
||||||
|
|
||||||
while low <= high do
|
while low <= high do
|
||||||
local mid = math.floor((low + high) / 2)
|
local mid = math.floor((low + high) / 2)
|
||||||
local guess = table[mid]
|
local guess = array[mid]
|
||||||
|
|
||||||
if guess == value then
|
if guess == value then
|
||||||
return mid
|
return mid
|
||||||
@@ -18,7 +18,7 @@ function binary_search(table, value)
|
|||||||
return nil
|
return nil
|
||||||
end
|
end
|
||||||
|
|
||||||
local my_table = {1, 3, 5, 7, 9}
|
local my_array = {1, 3, 5, 7, 9}
|
||||||
|
|
||||||
print(binary_search(my_table, 3)) -- => 2
|
print(binary_search(my_array, 3)) -- => 2
|
||||||
print(binary_search(my_table, -1)) -- => nil
|
print(binary_search(my_array, -1)) -- => nil
|
||||||
Reference in New Issue
Block a user