[swift-evolution] sortBy, minElementBy and maxElementBy methods

Jordan Rose jordan_rose at apple.com
Tue Jan 5 17:53:30 CST 2016


> On Dec 31, 2015, at 12:20, Brent Royal-Gordon via swift-evolution <swift-evolution at swift.org> wrote:
> 
> 2. It forces a naïve implementation, which may not be the best idea. In the Perl world, for instance, we would usually use a Schwartzian transform to implement this, particularly if the key might be expensive to compute:
> 
> 	array.map { ($0, sortKey($0)) }.sort { $0.1 < $1.1 }.map { $0.0 }

+1 and -1 to this. Computing the sort key N times instead of 2*(# of comparisons) can be a big win sometimes. On the other hand, allocating memory for the sort keys might be a net loss, especially if the collection being sorted is large. I guess that means it's better to be made explicit, but it would be nice™ if it were more convenient than it is now. Brent's way does a lot of copies; I tried to avoid that but quickly ran into trouble…

var keys = array.map { $0.key }
array.sort { ??? }

…because the current 'sort' takes a comparator, which just takes values, not indices.

Jordan
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <https://lists.swift.org/pipermail/swift-evolution/attachments/20160105/7538a4c9/attachment.html>


More information about the swift-evolution mailing list