Efficient sort function allowing own test and swap function as parameter

Alaindevos devosalain at ymail.com
Thu Oct 8 08:23:23 UTC 2020


On Wednesday, 7 October 2020 at 11:05:39 UTC, WebFreak001 wrote:
> 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);
>     }

This was what I was looking for. This zip combined with sort is 
powerful.


More information about the Digitalmars-d-learn mailing list