This is done with a straight decorate-sort-undecorate (<a href="http://en.wikipedia.org/wiki/Schwartzian_transform" rel="nofollow">http://en.wikipedia.org/wiki/Schwartzian_transform</a>). In the simplest case, and in Python:<p><pre><code> "".join(sorted("ccbaba", key=lambda c: "cba".index(c)))
</code></pre>
gives "ccbbaa" as the result.<p>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:<p><pre><code> order = {c: i for i, c in enumerate("bca")}
"".join(sorted("ccbaba", key=lambda c: order[c]))</code></pre>