What a smart way to implement OrderBy / ThenBy?

I implement the LINQ clone in Lua, but this is not very relevant here, and I have most of the functions performed (enumerated / requested, not a precompiler), but cannot come up with a smart way to implement Order By ThenBy.

I am currently sorting once and then placing in new lists and then sorting these subcategories and finally combining the results again, but it seems very wasteful and inefficient, I'm sure someone figured out a reasonable way to do this (better algorithm), but I have no idea what it is. Any tips on how to efficiently execute OrderBy / Thenby?

Note. The constructions of the language and the language, I hope, are not relevant here. I am looking for a generalized algorithm, just as they say that binary sorting can be done in any language.

Edit: I am currently working on LINQ to Object, so any ideas how this would be done in particular would be great. I assume that OrberBy / ThenBy is 2 function calls, not one, but I could be wrong.

+5
source share
2 answers

, , . , , :

int compareNames(Name n1, Name n2)
{
    if (n1.LastName < n2.LastName) {
        return -1;
    } else if (n1.LastName > n2.LastName) {
        return 1;
    } else if (n1.FirstName < n2.FirstName) {
        return -1;
    } else if (n1.FirstName > n2.FirstName) {
        return 1;
    } else {
        return 0;
    }
}

, FirstName, , LastName .

+3

, :

function(lh,rh)
    if lh.first < rh.first then
        return true
    elseif lh.second < rh.second then
        return true
    end
    return false
end

, true, , :

tests={}
tests[1]=function(lh,rh) 
    return lh.first < rh.first
end
tests[2]=function(lh,rh)
    return lh.second < rh.second
end

function(lh,rh)
    local res=true
    local k,v
    for k,v in ipairs(tests) do
        res = v(lh,rh)
        if res then break end
    end
    return res
end
+1

All Articles