Quicksort

This nice Quicksort program, shows the power and compactness of Forth. The code is adapted from a program originally designed by Wil Baden in 1983. The sort operates on an array of cell-sized items that could even include pointers to data structures larger than a cell.

Please respect the original copyright by including it in any usage or adaptation of this code in any other websites or programs.

(* Copyright (c) 2011 the authors listed at the following URL, and/or the authors of referenced articles or incorporated external code:  http://en.literateprograms.org/Quicksort_(Forth)?action=history&offset=20070731173044  Permission is hereby granted, free of charge, to any person obtaining  a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish,  distribute, sublicense, and/or sell copies of the Software, and to  permit persons to whom the Software is furnished to do so, subject to  the following conditions:  The above copyright notice and this permission notice shall be  included in all copies or substantial portions of the Software.  THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,  EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF  MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.  IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY  CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,  TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE  SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.*) -1 cells constant -cell : cell-  -cell + ; defer lessthan ( a@ b@ -- ? )  ' < is lessthan : mid ( l r -- mid ) over - 2/ -cell and + ; : exch ( addr1 addr2 -- ) dup @ >r over @ swap ! r> swap ! ; : part ( l r -- l r r2 l2 ) 2dup mid @ >r ( r: pivot ) 2dup begin swap begin dup @ r@ lessthan while cell+ repeat swap begin r@ over @ lessthan while cell- repeat 2dup <= if 2dup exch >r cell+ r> cell- then 2dup > until r> drop ; : qsort ( l r -- ) part swap rot \ 2over 2over - + < if 2swap then 2dup < if recurse else 2drop then 2dup < if recurse else 2drop then ; : sort ( array len -- ) dup 2 < if 2drop exit then 1- cells over + qsort ; create test 4, 7 , 1 , 0 , 3 , 9 , 6 , 8 , 2 , 5 , : main test 10 sort 10 0 do test i cells + @. loop cr ; main bye