-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathwordlookup.lua
42 lines (40 loc) · 1.1 KB
/
wordlookup.lua
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
local default_fcompval = function( value ) return value end
local fcompf = function( a,b )
return a < b
end
local fcompr = function( a,b )
return a > b
end
function table.binsearch( t, value, fcompval, reversed )
-- Initialise functions
local fcompval = fcompval or default_fcompval
local fcomp = reversed and fcompr or fcompf
-- Initialise numbers
local iStart,iEnd,iMid = 1,#t,0
-- Binary Search
while iStart <= iEnd do
-- calculate middle
iMid = math.floor( (iStart+iEnd)/2 )
-- get compare value
local value2 = fcompval( t[iMid] )
-- get all values that match
value = value:lower()
value2 = value2:lower()
if value == value2 then
local tfound,num = { iMid,iMid },iMid - 1
while value == fcompval( t[num] ) do
tfound[1],num = num,num - 1
end
num = iMid + 1
while value == fcompval( t[num] ) do
tfound[2],num = num,num + 1
end
return tfound
-- keep searching
elseif fcomp( value, value2 ) then
iEnd = iMid - 1
else
iStart = iMid + 1
end
end
end