Skip to content

Commit dff0f33

Browse files
zhangjiongwxegonSchiele
authored andcommitted
Add Lua code for chapter 1
1 parent 429710a commit dff0f33

File tree

1 file changed

+24
-0
lines changed

1 file changed

+24
-0
lines changed
Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,24 @@
1+
function binary_search(table, value)
2+
-- Lua arrays start with 1
3+
local low, high = 1, #table
4+
5+
while low <= high do
6+
local mid = math.floor((low + high) / 2)
7+
local guess = table[mid]
8+
9+
if guess == value then
10+
return mid
11+
elseif guess > value then
12+
high = mid - 1
13+
else
14+
low = mid + 1
15+
end
16+
end
17+
18+
return nil
19+
end
20+
21+
local my_table = {1, 3, 5, 7, 9}
22+
23+
print(binary_search(my_table, 3)) -- => 2
24+
print(binary_search(my_table, -1)) -- => nil

0 commit comments

Comments
 (0)