| • Science | • People | • Locations | • Timeline |
sort =: ]`(($:@: ((}.<:{.)#}.))
,{.,
($:@: ((}.> {.)#}.))) @. (*@#)
DEFINE sort == [small][]
[uncons [>] split]
swap] dip cons concat] binrec .
sort [] = []
sort (pivot:rest) = sort [ y | y <- rest; y <= pivot ]
++ [pivot] ++
sort [ y | y <- rest; y > pivot ]
sort () == id
sort pivot,,rest == ( self : rest[rest <= pivot] )
, pivot ,
( self : rest[rest > pivot] )
The following Haskell code is almost self explanatory but can suffer from inefficiencies because it crawls through the list "rest" twice, once for each list comprehension. A smart implementation can perform optimizations to prevent this inefficiency, but these are not required by the language.
sort :: (Ord a) => [a] -> [a]
sort [] = []
sort (pivot:rest) = sort [y | y <- rest, y < pivot]
++ [pivot] ++
sort [y | y <- rest, y >=pivot]
The following Erlang code sorts lists of items of any type.
qsort([]) -> [];
qsort([Pivot|Rest]) ->
qsort([ X || X <- Rest, X < Pivot]) ++ [Pivot] ++ qsort([ Y || Y <- Rest, Y >= Pivot]).
val sort : 'a list -> 'a list =
# let rec sort array = match array with
[] -> []
| pivot::rest -> let left,right = List.partition (function x -> x < pivot) rest
in (sort left) @ pivot::(sort right);;
(defun partition (fun array)
(list (remove-if-not fun array) (remove-if fun array)))
(defun sort (array)
(if (null array) nil
(let ((part (partition (lambda (x) (< x (car array))) (cdr array))))
(append (sort (car part)) (cons (car array) (sort (cadr part)))))))
def sort(array)
return [] if array.empty?
pivot = array[0]
left, right = array[1..-1].partition { |y| y <= pivot }.map { |a| sort(a) }
left + [ pivot ] + right
end
#include
#include
#include
template
void sort(T begin, T end) {
if (begin != end) {
T middle = partition (begin, end, bind2nd(
less::value_type>(), *begin));
sort (begin, middle);
sort (max(begin + 1, middle), end);
}
}
The following Python implementation uses a more efficient partitioning strategy:
def partition(array, begin, end, cmp):
while begin < end:
while begin < end:
if cmp(array[begin], array[end]):
(array[begin], array[end]) = (array[end], array[begin])
break
end -= 1
while begin < end:
if cmp(array[begin], array[end]):
(array[begin], array[end]) = (array[end], array[begin])
break
begin += 1
return begin
def sort(array, cmp=lambda x, y: x > y, begin=None, end=None):
if begin is None: begin = 0
if end is None: end = len(array)
if begin < end:
i = partition(array, begin, end-1, cmp)
sort(array, cmp, begin, i)
sort(array, cmp, i+1, end)
A more elegant implementation:
def qsort(L):
if L == []: return []
return qsort([x for x in L[1:] if x< L[0) + L[0:1] + \
qsort([x for x in L[1:] if x>=L[0]])