MC logo

Quicksort

  Prolog Examples

<<Insertion Sort sortquick.pl
% The split(A,Small,Large,List) relation describes the work of the
% quicksort partitioning (split) algorithm.  It means that elements
% of List contain exactly all the elements of Small and Large, and the item A,
% and all the members of small are < A, and all the members of large are
% >= A.
split(_,[],[],[]).
split(A,[S|Smalltail],Large,[S|Tail]) :- S < A, split(A,Smalltail,Large,Tail).
split(A,Small,[S|Largetail],[S|Tail]) :- S >= A, split(A,Small,Largetail,Tail).

% Perform sorting by quicksort.
sorted([], []).
sorted([Pivot|Tail], S) :- 
        split(Pivot, Small, Large, Tail),
        sorted(Small,SSmall), sorted(Large,SLarge),
        append(SSmall, [Pivot|SLarge], S).
<<Insertion Sort