Zipped sorting

bearophile bearophileHUGS at lycos.com
Mon Sep 24 19:18:43 PDT 2012


This line of code sorts two arrays in "lock step", according to 
the items of the first array:

zip(first, second).sort!q{a[0] < b[0]}();

This code is handy, nice looking, short and sufficiently easy to 
recognize once you have seen it before.

It's one case where D code is better than a Python version (and 
this returns two tuples instead of two lists):

first, second = zip(*sorted(izip(first, second), 
key=itemgetter(0)))

But with DMD on shortish arrays of about 20-30 items (each one 24 
bytes long) I've seen that D code 3-5 times slower (to be sure of 
such timings I have to write down a proper benchmark) than 
sorting the items with simple manually written sorting D code, 
like a bubble sort or something similar (where inside swaps items 
of both arrays). So if this sorting is done in inner loops or 
critical parts of code, you can't use that zip+sort :-(

Bye,
bearophile


More information about the Digitalmars-d-learn mailing list