Previous Next Contents

22. Sorting

LISP provides two primitives for sorting: sort and stable-sort.

> (sort '(2 1 5 4 6) #'<)
(1 2 4 5 6)
> (sort '(2 1 5 4 6) #'>)
(6 5 4 2 1)

The first argument to sort is a list; the second is a comparison function. The sort function does not guarantee stability: if there are two elements a and b such that (and (not (< a b)) (not (< b a))), sort may arrange them in either order. The stable-sort function is exactly like sort, except that it guarantees that two equivalent elements appear in the sorted list in the same order that they appeared in the original list.

Be careful: sort is allowed to destroy its argument, so if the original sequence is important to you, make a copy with the copy-list or copy-seq/ function.

Previous Next Contents