1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42
|
<HTML>
<HEAD>
<TITLE>Common LISP Hints: Sorting</TITLE>
</HEAD>
<BODY>
<A HREF="LISP-tutorial-21.html"><IMG SRC="prev.gif" ALT="Previous"></A>
<A HREF="LISP-tutorial-23.html"><IMG SRC="next.gif" ALT="Next"></A>
<A HREF="LISP-tutorial.html#toc22"><IMG SRC="toc.gif" ALT="Contents"></A>
<HR>
<H2><A NAME="s22">22. Sorting</A></H2>
<P>LISP provides two primitives for sorting: <CODE>sort</CODE> and <CODE>stable-sort</CODE>.</P>
<P>
<BLOCKQUOTE><CODE>
<PRE>
> (sort '(2 1 5 4 6) #'<)
(1 2 4 5 6)
> (sort '(2 1 5 4 6) #'>)
(6 5 4 2 1)
</PRE>
</CODE></BLOCKQUOTE>
</P>
<P>The first argument to <CODE>sort</CODE> is a list; the second is a comparison
function. The <CODE>sort</CODE> function does not guarantee stability: if there are
two elements <CODE>a</CODE> and <CODE>b</CODE> such that <CODE>(and (not (< a b)) (not
(< b a)))</CODE>, sort
may arrange them in either order. The <CODE>stable-sort</CODE> function is exactly
like <CODE>sort</CODE>, except that it guarantees that two equivalent elements
appear in the sorted list in the same order that they appeared in the
original list.</P>
<P>Be careful: <CODE>sort</CODE> is allowed to destroy its argument, so if the original
sequence is important to you, make a copy with the <CODE>copy-list</CODE> or
<CODE>copy</CODE>-seq/ function.</P>
<HR>
<A HREF="LISP-tutorial-21.html"><IMG SRC="prev.gif" ALT="Previous"></A>
<A HREF="LISP-tutorial-23.html"><IMG SRC="next.gif" ALT="Next"></A>
<A HREF="LISP-tutorial.html#toc22"><IMG SRC="toc.gif" ALT="Contents"></A>
</BODY>
</HTML>
|