Skip to content

Sorting with order arrays

forum.codecall.net
1 pointfayyazkl1 comment
On HN

Comments

This is done with a straight decorate-sort-undecorate (http://en.wikipedia.org/wiki/Schwartzian_transform). In the simplest case, and in Python:

    "".join(sorted("ccbaba", key=lambda c: "cba".index(c)))
gives "ccbbaa" as the result.

The performance is a function of the query string length and the order string length, because str.index is a linear search. The obvious speedup, should the order string be extremely long, is to turn the order string into a lookup table:

    order = {c: i for i, c in enumerate("bca")}
    "".join(sorted("ccbaba", key=lambda c: order[c]))
AboutSource Built by g1lg1l

Hackerly is an independent reader for Hacker News, built on the public HN API. Not affiliated with Y Combinator.