Sorting in D Programming Language

Our example demonstrates sorting in D using the standard library. We’ll look at sorting for built-in types first.

import std.stdio;
import std.algorithm;
import std.array;

void main()
{
    // Sorting functions work for any comparable built-in type.
    string[] strs = ["c", "a", "b"];
    strs.sort();
    writeln("Strings: ", strs);

    // An example of sorting integers.
    int[] ints = [7, 2, 4];
    ints.sort();
    writeln("Ints:    ", ints);

    // We can also check if a array is already in sorted order.
    bool s = ints.isSorted();
    writeln("Sorted:  ", s);
}

To run the program, save it as sorting.d and use the D compiler (dmd) to compile and run:

$ dmd -run sorting.d
Strings: ["a", "b", "c"]
Ints:    [2, 4, 7]
Sorted:  true

In this D example, we use the std.algorithm module which provides sorting functionality. The sort() function is used to sort arrays in-place. It works with any type that defines comparison operators.

The isSorted() function checks if an array is already in sorted order.

Note that unlike Go, D’s standard library functions for sorting and checking sorted status are methods on arrays rather than standalone functions. This makes the syntax slightly different, but the functionality is very similar.