As far as I know the best sorting algorithms written in Prolog directly, without reference to any special built-ins use some form of merge sort.
A frequent optimization is to start merging not with lists of length 1 but with already sorted segments.
That is, to sort the list [4,5,3,6,2,7,1,2]
, the lists [4,5]
,[3,6]
,[2,7]
,[1,2]
would be merged.
This can be optimized even further by assembling sorted lists not only in ascending direction, but also in the other direction. For the example above this would mean that the sorted segment is assembled as follows:
[4,5|_]
[3,4,5|_]
[3,4,5,6|_]
...
Note that in Prolog it is straight forward to extend a list both in the beginning and at the end.
Thus, we have to merge [1,2,3,4,5,6,7]
and [2]
only.
A current system that uses the original implementation (~1984) of Richard O'Keefe is Ciao-Prolog in
ciao-1.15/lib/sort.pl
.