Efficient sort function allowing own test and swap function as parameter

WebFreak001 d.forum at webfreak.org
Wed Oct 7 11:05:39 UTC 2020


On Tuesday, 6 October 2020 at 22:18:39 UTC, Alaindevos wrote:
> I have a large table consisting of two columns.One with 
> words.Another with frequencies. I want to sort them efficiently 
> according to the names or frequency.
> For this I need an efficient sort function where I can plugin 
> my proper test of order, and proper swap. Currently I do it 
> using an own written bubble sort that doesn't scale well.

you can use std.range:zip with std.algorithm:sort:

     import std;
     void main()
     {
         string[] names = ["Bob", "Alice", "Foo", "Bar"];
         int[] freq = [5, 7, 1, 6];

         zip(names, freq).sort!"a[0] < b[0]"; // sort by name
         writeln(names);
         writeln(freq);

         zip(names, freq).sort!"a[1] < b[1]"; // sort by frequency
         writeln(names);
         writeln(freq);
     }


More information about the Digitalmars-d-learn mailing list