1

I have written a binary search function in Lua from my memory of how it works in Python which works on a single array (table).

    function bisect_left(a, x, lo, hi)
        lo = lo or 1
        hi = hi or nil
        if lo < 0 then
            error('lo must be non-negative')
        end
        if hi == nil then
            hi = #a
        end
        while lo < hi do
            mid = math.floor((lo+hi) / 2)
            if a[mid] < x then 
                lo = mid+1
            else
                hi = mid
            end
        end
        return lo
     end

but then I encountered needing to search a sorted array of arrays (table of tables). They are sorted by index 1

squares = {{300, 400, 123456, 9}, {400, 500, 323456, 9}, {420, 610, 5123456, 9}, {530, 700, 8123456, 9}, {840, 960, 9123456, 1}}

In Python I would do something like overload the comparison operator cmp like

Class overload(object):
    def __init__(self, value, index):
        self.value = value
        self.index = index
    def __cmp__(self, other):
        return cmp(self.value, other[self.index])

What is the fastest way to do this in Lua? I can think of (I presume) slow ways to do it but my functional programming inexperience makes me wonder if there is a way I would never guess.

3
  • Shouldn't return lo be after the loop, not inside the loop? Commented Oct 22, 2013 at 15:52
  • 1
    I, guess, You could use __eq, __le and __lt Metatable events for this purpose. And __newindex for generating proper table. Trying to come up with simple explanatory code snippet. Commented Oct 22, 2013 at 15:53
  • thanks dasblinkenlight! Been writing lua for 1 day and all the "end"'s keep tripping me up Commented Oct 22, 2013 at 15:57

1 Answer 1

2

First, look at what's your comparator in the first example. Let's take a simple line:

if lo < 0 then

This could be written as something like:

if numericCompare(lo, 0) then

numericCompare being obviously function numericCompare(a,b) return a < b end.

Well then, change all the comparisons to something you might call tableCompare, and implement said comparator, presumably as

function tableCompare(a,b)
    return a[1] < b[1]
end

In general, tab[1] access should be rather fast due to the nature of Lua's tables. Code it, profile, and only then try to optimize.

Yoy can overload operators in Lua, but in that case I think that taking the comparator as parameter and naming it explicitely is slightly more readable.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.