Search code examples
listsortingd

How to sort DList?


How to sort DList and SList in-place?

In Python we can do list.sort(), in Java - Collections.sort(linkedList, new Comparator ...)

I can't figure out how to do the same in D.


Solution

  • Sorting a linked list is inefficient which is why sort requires a random access range as input. You probably want to either use arrays with direct memory access:

    import std.algorithm, std.container, std.stdio;
    void main()
    {
        auto list = DList!int(2, 1, 3);
        list[].array.sort.release.writeln; // or directly start with an array
    }
    

    Open on run.dlang.io.

    Or use sth. intrinsically sorted like a Heap or RBTree:

    import std.algorithm, std.container, std.stdio;
    void main()
    {
        auto list = DList!int(2, 1, 3);
        list[].redBlackTree[].writeln;
    }
    

    Open on run.dlang.io.