Newsgroups: comp.lang.dylan
Path: cantaloupe.srv.cs.cmu.edu!das-news2.harvard.edu!news2.near.net!news.mathworks.com!udel!gatech!swrinde!sdd.hp.com!news.cs.indiana.edu!jsobel@cs.indiana.edu
From: "Jonathan Sobel" <jsobel@cs.indiana.edu>
Subject: Re: QuickSort function?
Message-ID: <1995Mar8.124159.24200@news.cs.indiana.edu>
Organization: Computer Science, Indiana University
References: <16987.9503021647@bessie.harlequin.co.uk>
Date: Wed, 8 Mar 1995 12:41:55 -0500
Lines: 46

In article <16987.9503021647@bessie.harlequin.co.uk>,
Paul Haahr <haahr@harlequin.co.uk> wrote:
>Here's the one from the Stanford integer benchmarks, rewritten, though
>not particularly idiomatically, in Dylan.

Here's a version of quicksort for lists in a bit more Dylan-ish style.
It also has the extra benefit of being in a form that's very easy to
explain to my students (which is why I use it).  This is mostly a
translation of the quicksort used in _Scheme_and_the_Art_of_
_Programming_ by Springer and Friedman.

					Jonathan Sobel
					jsobel@cs.indiana.edu



// This is a fairly naive quicksort for lists.  It simply chooses the
// first item in the list as the pivot, so it's possible to get the
// infamous quadratic-quicksort behavior.

define method quicksort (data :: <list>) => sorted-data :: <list>;
  if (empty?(data) | empty?(tail(data)))
    data;
  else
    collect(head(data), tail(data), #(), #());
  end if;
end method quicksort;


// This function goes through the data, collecting items which are
// less than the pivot into left-side those greater than the pivot
// into right-side.  When it's done, it quicksorts the two halves and
// puts them back together again (with the pivot in the middle).

define method collect (pivot, data :: <list>, left-side, right-side)
 => sorted-data :: <list>;
  case
    empty?(data) =>
      concatenate(quicksort(left-side),
		  pair(pivot, quicksort(right-side)));
    (pivot < head(data)) =>
      collect(pivot, tail(data), left-side, pair(head(data), right-side));
    otherwise =>
      collect(pivot, tail(data), pair(head(data), left-side), right-side);
  end case;
end method collect;
