python3 << 'EOF'
import urllib.request
url = 'https://r.jina.ai/http://rosettacode.org/wiki/Sorting_algorithms/Quicksort'
req = urllib.request.Request(url, headers={'User-Agent': 'Mozilla/5.0'})
with urllib.request.urlopen(req, timeout=20) as response:
    html = response.read().decode('utf-8', errors='ignore')
# The C++ section starts around the #include <algorithm>
idx = html.find('#include <algorithm> // for std::partition')
# Go back to find section header
start = html.rfind('\n\n', 0, idx)
if start < 0:
    start = html.rfind('##', 0, idx)
# Find end of C++ section (next ## section)
end = html.find('##', idx)
if end < 0:
    end = len(html)
content = html[start:end]
print(content)
EOF


#include <iterator>
#include <algorithm> // for std::partition
#include <functional> // for std::less

// helper function for median of three
template<typename T>
 T median(T t1, T t2, T t3)
{
  if (t1 < t2)
  {
    if (t2 < t3)
      return t2;
    else if (t1 < t3)
      return t3;
    else
      return t1;
  }
  else
  {
    if (t1 < t3)
      return t1;
    else if (t2 < t3)
      return t3;
    else
      return t2;
  }
}

// helper object to get <= from <
template<typename Order> struct non_strict_op:
  public std::binary_function<typename Order::second_argument_type,
                              typename Order::first_argument_type,
                              bool>
{
  non_strict_op(Order o): order(o) {}
  bool operator()(typename Order::second_argument_type arg1,
                  typename Order::first_argument_type arg2) const
  {
    return !order(arg2, arg1);
  }
private:
  Order order;
};

template<typename Order> non_strict_op<Order> non_strict(Order o)
{
  return non_strict_op<Order>(o);
}

template<typename RandomAccessIterator,
         typename Order>
 void quicksort(RandomAccessIterator first, RandomAccessIterator last, Order order)
{
  if (first != last && first+1 != last)
  {
    typedef typename std::iterator_traits<RandomAccessIterator>::value_type value_type;
    RandomAccessIterator mid = first + (last - first)/2;
    value_type pivot = median(*first, *mid, *(last-1));
    RandomAccessIterator split1 = std::partition(first, last, std::bind2nd(order, pivot));
    RandomAccessIterator split2 = std::partition(split1, last, std::bind2nd(non_strict(order), pivot));
    quicksort(first, split1, order);
    quicksort(split2, last, order);
  }
}

template<typename RandomAccessIterator>
 void quicksort(RandomAccessIterator first, RandomAccessIterator last)
{
  quicksort(first, last, std::less<typename std::iterator_traits<RandomAccessIterator>::value_type>());
}


A simpler version of the above that just uses the first element as the pivot and only does one "partition".

#include <iterator>
#include <algorithm> // for std::partition
#include <functional> // for std::less

template<typename RandomAccessIterator,
         typename Order>
 void quicksort(RandomAccessIterator first, RandomAccessIterator last, Order order)
{
  if (last - first > 1)
  {
    RandomAccessIterator split = std::partition(first+1, last, std::bind2nd(order, *first));
    std::iter_swap(first, split-1);
    quicksort(first, split-1, order);
    quicksort(split, last, order);
  }
}

template<typename RandomAccessIterator>
 void quicksort(RandomAccessIterator first, RandomAccessIterator last)
{
  quicksort(first, last, std::less<typename std::iterator_traits<RandomAccessIterator>::value_type>());
}

Clojure

A very Haskell-like solution using list comprehensions and lazy evaluation.

(defn qsort [L]
  (if (empty? L)
      '()
      (let [[pivot & L2] L]
           (lazy-cat (qsort (for [y L2 :when (<  y pivot)] y))
                     (list pivot)
                     (qsort (for [y L2 :when (>= y pivot)] y))))))


Another short version (using quasiquote):

(defn qsort [[pvt & rs]]
  (if pvt
    `(~@(qsort (filter #(<  % pvt) rs))
      ~pvt
      ~@(qsort (filter #(>= % pvt) rs)))))


Another, more readable version (no macros):

(defn qsort [[pivot & xs]]
  (when pivot
    (let [smaller #(< % pivot)]
      (lazy-cat (qsort (filter smaller xs))
                [pivot]
                (qsort (remove smaller xs))))))


A 3-group quicksort (fast when many values are equal):

(defn qsort3 [[pvt :as coll]]
  (when pvt
    (let [{left -1 mid 0 right 1} (group-by #(compare % pvt) coll)]
      (lazy-cat (qsort3 left) mid (qsort3 right)))))


A lazier version of above (unlike group-by, filter returns (and reads) a lazy sequence)

(defn qsort3 [[pivot :as coll]]
  (when pivot
    (lazy-cat (qsort (filter #(< % pivot) coll))
              (filter #{pivot} coll)
              (qsort (filter #(> % pivot) coll)))))

COBOL
Works with: Visual COBOL
       IDENTIFICATION DIVISION.
       PROGRAM-ID. quicksort RECURSIVE.

       DATA DIVISION.
       LOCAL-STORAGE SECTION.
       01  temp                   PIC S9(8).

       01  pivot                  PIC S9(8).

       01  left-most-idx          PIC 9(5).
       01  right-most-idx         PIC 9(5).

       01  left-idx               PIC 9(5).
       01  right-idx              PIC 9(5).

       LINKAGE SECTION.
       78  Arr-Length             VALUE 50.

       01  arr-area.
           03  arr                PIC S9(8) OCCURS Arr-Length TIMES.

       01  left-val               PIC 9(5).
       01  right-val              PIC 9(5).

       PROCEDURE DIVISION USING REFERENCE arr-area, OPTIONAL left-val,
               OPTIONAL right-val.
           IF left-val IS OMITTED OR right-val IS OMITTED
               MOVE 1 TO left-most-idx, left-idx
               MOVE Arr-Length TO right-most-idx, right-idx
           ELSE
               MOVE left-val TO left-most-idx, left-idx
               MOVE right-val TO right-most-idx, right-idx
           END-IF

           IF right-most-idx - left-most-idx < 1
               GOBACK
           END-IF

           COMPUTE pivot = arr ((left-most-idx + right-most-idx) / 2)

           PERFORM UNTIL left-idx > right-idx
               PERFORM VARYING left-idx FROM left-idx BY 1
                   UNTIL arr (left-idx) >= pivot
               END-PERFORM

               PERFORM VARYING right-idx FROM right-idx BY -1
                   UNTIL arr (right-idx) <= pivot
               END-PERFORM

               IF left-idx <= right-idx
                   MOVE arr (left-idx) TO temp
                   MOVE arr (right-idx) TO arr (left-idx)
                   MOVE temp TO arr (right-idx)

                   ADD 1 TO left-idx
                   SUBTRACT 1 FROM right-idx
               END-IF
           END-PERFORM

           CALL "quicksort" USING REFERENCE arr-area,
               CONTENT left-most-idx, right-idx
           CALL "quicksort" USING REFERENCE arr-area, CONTENT left-idx,
               right-most-idx

           GOBACK
           .

CoffeeScript
quicksort = ([x, xs...]) ->
  return [] unless x?
  smallerOrEqual = (a for a in xs when a <= x)
  larger = (a for a in xs when a > x)
  (quicksort smallerOrEqual).concat(x).concat(quicksort larger)

Common Lisp

The functional programming way

(defun quicksort (list &aux (pivot (car list)) )
  (if (cdr list)
      (nconc (quicksort (remove-if-not #'(lambda (x) (< x pivot)) list))
             (remove-if-not #'(lambda (x) (= x pivot)) list)
             (quicksort (remove-if-not #'(lambda (x) (> x pivot)) list)))
      list))


With flet

(defun qs (list)
  (if (cdr list)
      (flet ((pivot (test)
               (remove (car list) list :test-not test)))
        (nconc (qs (pivot #'>)) (pivot #'=) (qs (pivot #'<))))
      list))


In-place non-functional

(defun quicksort (sequence)
  (labels ((swap (a b) (rotatef (elt sequence a) (elt sequence b)))
           (sub-sort (left right)
             (when (< left right)
               (let ((pivot (elt sequence right))
                     (index left))
                 (loop for i from left below right
                       when (<= (elt sequence i) pivot)
                         do (swap i (prog1 index (incf index))))
                 (swap right index)
                 (sub-sort left (1- index))
                 (sub-sort (1+ index) right)))))
    (sub-sort 0 (1- (length sequence)))
    sequence))


Functional with destructuring

(defun quicksort (list)
  (when list
    (destructuring-bind (x . xs) list
      (nconc (quicksort (remove-if (lambda (a) (> a x)) xs))
             `(,x)
             (quicksort (remove-if (lambda (a) (<= a x)) xs))))))

Cowgol
include "cowgol.coh";

# Comparator interface, on the model of C, i.e:
# foo < bar => -1, foo == bar => 0, foo > bar => 1
typedef CompRslt is int(-1, 1);
interface Comparator(foo: intptr, bar: intptr): (rslt: CompRslt);

# Quicksort an array of pointer-sized integers given a comparator function
# (This is the closest you can get to polymorphism in Cowgol).
# Because Cowgol does not support recursion, a pointer to free memory
# for a stack must also be given.
sub qsort(A: [intptr], len: intptr, comp: Comparator, stack: [intptr]) is
    # The partition function can be taken almost verbatim from Wikipedia
    sub partition(lo: intptr, hi: intptr): (p: intptr) is
        # This is not quite as bad as it looks: /2 compiles into a single shift
        # and "@bytesof intptr" is always power of 2 so compiles into shift(s).
        var pivot := [A + (hi/2 + lo/2) * @bytesof intptr];
        var i := lo - 1;
        var j := hi + 1;
        loop
            loop
                i := i + 1;
                if comp([A + i*@bytesof intptr], pivot) != -1 then
                    break;
                end if;
            end loop;
            loop
                j := j - 1;
                if comp([A + j*@bytesof intptr], pivot) != 1 then
                    break;
                end if;
            end loop;
            if i >= j then
                p := j;
                return;
            end if;
            var ii := i * @bytesof intptr;
            var jj := j * @bytesof intptr;
            var t := [A+ii];
            [A+ii] := [A+jj];
            [A+jj] := t;
        end loop;
    end sub;

    # Cowgol lacks recursion, so we'll have to solve it by implementing
    # the stack ourselves.
    var sp: intptr := 0; # stack index
    sub push(n: intptr) is
        sp := sp + 1;
        [stack] := n;
        stack := @next stack;
    end sub;
    sub pop(): (n: intptr) is
        sp := sp - 1;
        stack := @prev stack;
        n := [stack];
    end sub;

    # start by sorting [0..length-1]
    push(len-1);
    push(0);
    while sp != 0 loop
        var lo := pop();
        var hi := pop();
        if lo < hi then
            var p := partition(lo, hi);
            push(hi);   # note the order - we need to push the high pair
            push(p+1);  # first for it to be done last
            push(p);
            push(lo);
        end if;
    end loop;
end sub;

# Test: sort a list of numbers
sub NumComp implements Comparator is
    # Compare the inputs as numbers
    if foo < bar then rslt := -1;
    elseif foo > bar then rslt := 1;
    else rslt := 0;
    end if;
end sub;

# Numbers
var numbers: intptr[] := {
    65,13,4,84,29,5,96,73,5,11,17,76,38,26,44,20,36,12,44,51,79,8,99,7,19,95,26
};

# Room for the stack
var stackbuf: intptr[256];

# Sort the numbers in place
qsort(&numbers as [intptr], @sizeof numbers, NumComp, &stackbuf as [intptr]);

# Print the numbers (hopefully in order)
var i: @indexof numbers := 0;
while i < @sizeof numbers loop
    print_i32(numbers[i] as uint32);
    print_char(' ');
    i := i + 1;
end loop;
print_nl();
Output:
4 5 5 7 8 11 12 13 17 19 20 26 26 29 36 38 44 44 51 65 73 76 79 84 95 96 99
Crystal
Translation of: Ruby
def quick_sort(a : Array(Int32)) : Array(Int32)
  return a if a.size <= 1
  p = a[0]
  lt, rt = a[1 .. -1].partition { |x| x < p }
  return quick_sort(lt) + [p] + quick_sort(rt)
end

a = [7, 6, 5, 9, 8, 4, 3, 1, 2, 0]
puts quick_sort(a) # => [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]

Curry

Copied from Curry: Example Programs.

-- quicksort using higher-order functions:

qsort :: [Int] -> [Int]
qsort []     = []
qsort (x:l)  = qsort (filter (<x) l) ++ x : qsort (filter (>=x) l)

goal = qsort [2,3,1,0]
D

A Functional version

import std.stdio : writefln, writeln;
import std.algorithm: filter;
import std.array;

T[] quickSort(T)(T[] xs) =>
  xs.length == 0 ? [] :
    xs[1 .. $].filter!(x => x< xs[0]).array.quickSort ~
    xs[0 .. 1] ~
    xs[1 .. $].filter!(x => x>=xs[0]).array.quickSort;

void main() =>
  [4, 65, 2, -31, 0, 99, 2, 83, 782, 1].quickSort.writeln;

Output:
[-31, 0, 1, 2, 2, 4, 65, 83, 99, 782]

A simple high-level version (same output):

import std.stdio, std.array;

T[] quickSort(T)(T[] items) pure nothrow {
    if (items.empty)
        return items;
    T[] less, notLess;
    foreach (x; items[1 .. $])
        (x < items[0] ? less : notLess) ~= x;
    return less.quickSort ~ items[0] ~ notLess.quickSort;
}

void main() {
    [4, 65, 2, -31, 0, 99, 2, 83, 782, 1].quickSort.writeln;
}


Often short functional sieves are not a true implementations of the Sieve of Eratosthenes: http://www.cs.hmc.edu/~oneill/papers/Sieve-JFP.pdf

Similarly, one could argue that a true QuickSort is in-place, as this more efficient version (same output):

import std.stdio, std.algorithm;

void quickSort(T)(T[] items) pure nothrow @safe @nogc {
    if (items.length >= 2) {
        auto parts = partition3(items, items[$ / 2]);
        parts[0].quickSort;
        parts[2].quickSort;
    }
}

void main() {
    auto items = [4, 65, 2, -31, 0, 99, 2, 83, 782, 1];
    items.quickSort;
    items.writeln;
}

Delphi
Works with: Delphi version 6.0
Library: SysUtils,StdCtrls

This quick sort routine is infinitely versatile. It sorts an array of pointers. The advantage of this is that pointers can contain anything, ranging from integers, to strings, to floating point numbers to objects. The way each pointer is interpreted is through the compare routine, which is customized for the particular situation. The compare routine can interpret each pointer as a string, an integer, a float or an object and it can treat those items in different ways. For example, the order in which it compares strings controls whether the sort is alphabetical or reverse alphabetical. In this case, I show an integer sort, an alphabetic string sort, a reverse alphabetical string sort and a string sort by length.

{Dynamic array of pointers}

type TPointerArray = array of Pointer;

procedure QuickSort(SortList: TPointerArray; L, R: Integer; SCompare: TListSortCompare);
{Do quick sort on items held in TPointerArray}
{SCompare controls how the pointers are interpreted}
var I, J: Integer;
var P,T: Pointer;
begin
repeat
        begin
        I := L;
        J := R;
        P := SortList[(L + R) shr 1];
        repeat
                begin
                while SCompare(SortList[I], P) < 0 do Inc(I);
                while SCompare(SortList[J], P) > 0 do Dec(J);
                if I <= J then
 <response clipped><NOTE>Due to the max output limit, only part of the full response has been shown to you.</NOTE>a;
  }

  var pivot = a[0];
  var less = [];
  var more = [];
  var pivotList = [];

  // Partition
  a.forEach((var i){
    if (i.compareTo(pivot) < 0) {
      less.add(i);
    } else if (i.compareTo(pivot) > 0) {
      more.add(i);
    } else {
      pivotList.add(i);
    }
  });

  // Recursively sort sublists
  less = quickSort(less);
  more = quickSort(more);

  // Concatenate results
  less.addAll(pivotList);
  less.addAll(more);
  return less;
}

void main() {
  var arr=[1,5,2,7,3,9,4,6,8];
  print("Before sort");
  arr.forEach((var i)=>print("$i"));
  arr = quickSort(arr);
  print("After sort");
  arr.forEach((var i)=>print("$i"));
}

E
def quicksort := {

    def swap(container, ixA, ixB) {
        def temp := container[ixA]
        container[ixA] := container[ixB]
        container[ixB] := temp
    }

    def partition(array, var first :int, var last :int) {
        if (last <= first) { return }

        # Choose a pivot
        def pivot := array[def pivotIndex := (first + last) // 2]

        # Move pivot to end temporarily
        swap(array, pivotIndex, last)

        var swapWith := first

        # Scan array except for pivot, and...
        for i in first..!last {
            if (array[i] <= pivot) {   # items ≤ the pivot
                swap(array, i, swapWith) # are moved to consecutive positions on the left
                swapWith += 1
            }
        }

        # Swap pivot into between-partition position.
        # Because of the swapping we know that everything before swapWith is less
        # than or equal to the pivot, and the item at swapWith (since it was not
        # swapped) is greater than the pivot, so inserting the pivot at swapWith
        # will preserve the partition.
        swap(array, swapWith, last)
        return swapWith
    }

    def quicksortR(array, first :int, last :int) {
        if (last <= first) { return }
        def pivot := partition(array, first, last)
        quicksortR(array, first, pivot - 1)
        quicksortR(array, pivot + 1, last)
    }

    def quicksort(array) { # returned from block
        quicksortR(array, 0, array.size() - 1)
    }
}
EasyLang
proc qsort left right &d[] .
   if left < right
      piv = d[left]
      mid = left
      for i = left + 1 to right
         if d[i] < piv
            mid += 1
            swap d[i] d[mid]
         .
      .
      swap d[left] d[mid]
      qsort left mid - 1 d[]
      qsort mid + 1 right d[]
   .
.
proc sort &d[] .
   qsort 1 len d[] d[]
.
d[] = [ 29 4 72 44 55 26 27 77 92 5 ]
sort d[]
print d[]
Output:
[ 4 5 26 27 29 44 55 72 77 92 ]

EchoLisp
(lib 'list) ;; list-partition

(define compare 0) ;; counter

(define (quicksort L compare-predicate: proc aux:  (part null))
(if  (<= (length L) 1) L
     (begin
     ;; counting the number of comparisons
     (set! compare (+ compare (length (rest L))))
      ;; pivot = first element of list
     (set! part (list-partition (rest L) proc (first L)))
     (append (quicksort (first part) proc )
            (list (first L))
            (quicksort (second part) proc)))))

Output:
(shuffle (iota 15))
    → (10 0 14 11 13 9 2 5 4 8 1 7 12 3 6)
(quicksort (shuffle (iota 15)) <)
    → (0 1 2 3 4 5 6 7 8 9 10 11 12 13 14)

;; random list of numbers in [0 .. n[
;; count number of comparisons
(define (qtest (n 10000))
        (set! compare 0)
        (quicksort (shuffle (iota n)) >)
        (writeln 'n n 'compare# compare ))

(qtest 1000)
  n     1000       compare#     12764
(qtest 10000)
  n     10000      compare#     277868
(qtest 100000)
  n     100000     compare#     6198601

Eero

Translated from Objective-C example on this page.

#import <Foundation/Foundation.h>

void quicksortInPlace(MutableArray array, const long first, const long last)
  if first >= last
    return
  Value pivot = array[(first + last) / 2]
  left := first
  right := last
  while left <= right
    while array[left] < pivot
      left++
    while array[right] > pivot
      right--
    if left <= right
      array.exchangeObjectAtIndex: left++, withObjectAtIndex: right--

  quicksortInPlace(array, first, right)
  quicksortInPlace(array, left, last)

Array quicksort(Array unsorted)
  a := []
  a.addObjectsFromArray: unsorted
  quicksortInPlace(a, 0, a.count - 1)
  return a


int main(int argc, const char * argv[])
  autoreleasepool
    a := [1, 3, 5, 7, 9, 8, 6, 4, 2]
    Log( 'Unsorted: %@', a)
    Log( 'Sorted: %@', quicksort(a) )
    b := ['Emil', 'Peg', 'Helen', 'Juergen', 'David', 'Rick', 'Barb', 'Mike', 'Tom']
    Log( 'Unsorted: %@', b)
    Log( 'Sorted: %@', quicksort(b) )

  return 0


Alternative implementation (not necessarily as efficient, but very readable)

#import <Foundation/Foundation.h>

implementation Array (Quicksort)

  plus: Array array, return Array =
    self.arrayByAddingObjectsFromArray: array

  filter: BOOL (^)(id) predicate, return Array
    array := []
    for id item in self
      if predicate(item)
        array.addObject: item
    return array.copy

  quicksort, return Array = self
    if self.count > 1
      id x = self[self.count / 2]
      lesser := self.filter: (id y | return y < x)
      greater := self.filter: (id y | return y > x)
      return lesser.quicksort + [x] + greater.quicksort

end

int main()
  autoreleasepool
    a := [1, 3, 5, 7, 9, 8, 6, 4, 2]
    Log( 'Unsorted: %@', a)
    Log( 'Sorted: %@', a.quicksort )
    b := ['Emil', 'Peg', 'Helen', 'Juergen', 'David', 'Rick', 'Barb', 'Mike', 'Tom']
    Log( 'Unsorted: %@', b)
    Log( 'Sorted: %@', b.quicksort )

  return 0

Output:
2013-09-04 16:54:31.780 a.out[2201:507] Unsorted: (
    1,
    3,
    5,
    7,
    9,
    8,
    6,
    4,
    2
)
2013-09-04 16:54:31.781 a.out[2201:507] Sorted: (
    1,
    2,
    3,
    4,
    5,
    6,
    7,
    8,
    9
)
2013-09-04 16:54:31.781 a.out[2201:507] Unsorted: (
    Emil,
    Peg,
    Helen,
    Juergen,
    David,
    Rick,
    Barb,
    Mike,
    Tom
)
2013-09-04 16:54:31.782 a.out[2201:507] Sorted: (
    Barb,
    David,
    Emil,
    Helen,
    Juergen,
    Mike,
    Peg,
    Rick,
    Tom
)

Eiffel

The

QUICKSORT


class:

class
        QUICKSORT [G -> COMPARABLE]

create
        make

feature {NONE} --Implementation

        is_sorted (list: ARRAY [G]): BOOLEAN
                require
                        not_void: list /= Void
                local
                        i: INTEGER
                do
                        Result := True
                        from
                                i := list.lower + 1
                        invariant
                                i >= list.lower + 1 and i <= list.upper + 1
                        until
                                i > list.upper
                        loop
                                Result := Result and list [i - 1] <= list [i]
                                i := i + 1
                        variant
                                list.upper + 1 - i
                        end
                end

        concatenate_array (a: ARRAY [G] b: ARRAY [G]): ARRAY [G]
                require
                        not_void: a /= Void and b /= Void
                do
                        create Result.make_from_array (a)
                        across
                                b as t
                        loop
                                Result.force (t.item, Result.upper + 1)
                        end
                ensure
                        same_size: a.count + b.count = Result.count
                end

        quicksort_array (list: ARRAY [G]): ARRAY [G]
                require
                        not_void: list /= Void
                local
                        less_a: ARRAY [G]
                        equal_a: ARRAY [G]
                        more_a: ARRAY [G]
                        pivot: G
                do
                        create less_a.make_empty
                        create more_a.make_empty
                        create equal_a.make_empty
                        create Result.make_empty
                        if list.count <= 1 then
                                Result := list
                        else
                                pivot := list [list.lower]
                                across
                                        list as li
                                invariant
                                        less_a.count + equal_a.count + more_a.count <= list.count
                                loop
                                        if li.item < pivot then
                                                less_a.force (li.item, less_a.upper + 1)
                                        elseif li.item = pivot then
                                                equal_a.force (li.item, equal_a.upper + 1)
                                        elseif li.item > pivot then
                                                more_a.force (li.item, more_a.upper + 1)
                                        end
                                end
                                Result := concatenate_array (Result, quicksort_array (less_a))
                                Result := concatenate_array (Result, equal_a)
                                Result := concatenate_array (Result, quicksort_array (more_a))
                        end
                ensure
                        same_size: list.count = Result.count
                        sorted: is_sorted (Result)
                end

feature -- Initialization

        make
                do
                end

        quicksort (a: ARRAY [G]): ARRAY [G]
                do
                        Result := quicksort_array (a)
                end

end


A test application:

class
        APPLICATION

create
        make

feature {NONE} -- Initialization

        make
                        -- Run application.
                local
                        test: ARRAY [INTEGER]
                        sorted: ARRAY [INTEGER]
                        sorter: QUICKSORT [INTEGER]
                do
                        create sorter.make
                        test := <<1, 3, 2, 4, 5, 5, 7, -1>>
                        sorted := sorter.quicksort (test)
                        across
                                sorted as s
                        loop
                                print (s.item)
                                print (" ")
                        end
                        print ("%N")
                end

end

Elena

ELENA 6.x :

import extensions;
import system'routines;
import system'collections;

extension op
{
    quickSort()
    {
        if (self.isEmpty()) { ^ self };

        var pivot := self[0];

        auto less := new ArrayList();
        auto pivotList := new ArrayList();
        auto more := new ArrayList();

        self.forEach::(item)
        {
            if (item < pivot)
            {
                less.append(item)
            }
            else if (item > pivot)
            {
                more.append(item)
            }
            else
            {
                pivotList.append(item)
            }
        };

        less := less.quickSort();
        more := more.quickSort();

        less.appendRange(pivotList);
        less.appendRange(more);

        ^ less
    }
}

public Program()
{
    var list := new int[]{3, 14, 1, 5, 9, 2, 6, 3};

    Console.printLine("before:", list.asEnumerable());
    Console.printLine("after :", list.quickSort().asEnumerable());
}
Output:
before:3,14,1,5,9,2,6,3
after :1,2,3,3,5,6,9,14

Elixir
defmodule Sort do
  def qsort([]), do: []
  def qsort([h | t]) do
    {lesser, greater} = Enum.split_with(t, &(&1 < h))
    qsort(lesser) ++ [h] ++ qsort(greater)
  end
end

Erlang

like haskell. Used by Measure_relative_performance_of_sorting_algorithms_implementations. If changed keep the interface or change Measure_relative_performance_of_sorting_algorithms_implementations

-module( quicksort ).

-export( [qsort/1] ).

qsort([]) -> [];
qsort([X|Xs]) ->
   qsort([ Y || Y <- Xs, Y < X]) ++ [X] ++ qsort([ Y || Y <- Xs, Y >= X]).


multi-process implementation (number processes = number of processor cores):

quick_sort(L) -> qs(L, trunc(math:log2(erlang:system_info(schedulers)))).

qs([],_) -> [];
qs([H|T], N) when N > 0  ->
    {Parent, Ref} = {self(), make_ref()},
    spawn(fun()-> Parent ! {l1, Ref, qs([E||E<-T, E<H], N-1)} end),
    spawn(fun()-> Parent ! {l2, Ref, qs([E||E<-T, H =< E], N-1)} end),
    {L1, L2} = receive_results(Ref, undefined, undefined),
    L1 ++ [H] ++ L2;
qs([H|T],_) ->
    qs([E||E<-T, E<H],0) ++ [H] ++ qs([E||E<-T, H =< E],0).

receive_results(Ref, L1, L2) ->
    receive
        {l1, Ref, L1R} when L2 == undefined -> receive_results(Ref, L1R, L2);
        {l2, Ref, L2R} when L1 == undefined -> receive_results(Ref, L1, L2R);
        {l1, Ref, L1R} -> {L1R, L2};
        {l2, Ref, L2R} -> {L1, L2R}
    after 5000 -> receive_results(Ref, L1, L2)
    end.

Emacs Lisp

Unoptimized

Library: seq.el
(require 'seq)

(defun quicksort (xs)
  (if (null xs)
      ()
    (let* ((head (car xs))
           (tail (cdr xs))
           (lower-part (quicksort (seq-filter (lambda (x) (<= x head)) tail)))
           (higher-part (quicksort (seq-filter (lambda (x) (> x head)) tail))))
      (append lower-part (list head) higher-part))))

ERRE
PROGRAM QUICKSORT_DEMO

DIM ARRAY[21]

!$DYNAMIC
DIM QSTACK[0]

!$INCLUDE="PC.LIB"

PROCEDURE QSORT(ARRAY[],START,NUM)
  FIRST=START               ! initialize work variables
  LAST=START+NUM-1
  LOOP
    REPEAT
      TEMP=ARRAY[(LAST+FIRST) DIV 2]  ! seek midpoint
      I=FIRST
      J=LAST
      REPEAT     ! reverse both < and > below to sort descending
      WHILE ARRAY[I]<TEMP DO
        I=I+1
        END WHILE
        WHILE ARRAY[J]>TEMP DO
          J=J-1
        END WHILE
        EXIT IF I>J
        IF I<J THEN SWAP(ARRAY[I],ARRAY[J]) END IF
        I=I+1
        J=J-1
      UNTIL NOT(I<=J)
      IF I<LAST THEN             ! Done
         QSTACK[SP]=I            ! Push I
         QSTACK[SP+1]=LAST       ! Push Last
         SP=SP+2
      END IF
      LAST=J
    UNTIL NOT(FIRST<LAST)

    EXIT IF SP=0
    SP=SP-2
    FIRST=QSTACK[SP]            ! Pop First
    LAST=QSTACK[SP+1]           ! Pop Last
  END LOOP
END PROCEDURE

BEGIN
   RANDOMIZE(TIMER)              ! generate a new series each run

                                 ! create an array
   FOR X=1 TO 21 DO              ! fill with random numbers
       ARRAY[X]=RND(1)*500       ! between 0 and 500
   END FOR
   PRIMO=6                       ! sort starting here
   NUM=10                        ! sort this many elements
   CLS
   PRINT("Before Sorting:";TAB(31);"After sorting:")
   PRINT("===============";TAB(31);"==============")
   FOR X=1 TO 21 DO              ! show them before sorting
      IF X>=PRIMO AND X<=PRIMO+NUM-1 THEN
         PRINT("==>";)
      END IF
      PRINT(TAB(5);)
      WRITE("
[The command completed with exit code 0.]
[Current working directory: /workspace]
[Python interpreter: /usr/local/bin/python]
[Command finished with exit code 0]