Algorithm Implementation/Sorting/Quicksort

Iterative version
function QuickSort(Array, Left, Right) var L2, R2, PivotValue begin Stack.Push(Left, Right);      // pushes Left, and then Right, on to a stack while not Stack.Empty do begin Stack.Pop(Left, Right);   // pops 2 values, storing them in Right and then Left repeat PivotValue := Array[(Left + Right) div 2]; L2 := Left; R2 := Right; repeat while Array[L2] < PivotValue do // scan left partition L2 := L2 + 1; while Array[R2] > PivotValue do // scan right partition R2 := R2 - 1; if L2 <= R2 then begin if L2 != R2 then Swap(Array[L2], Array[R2]); // swaps the data at L2 and R2 L2 := L2 + 1; R2 := R2 - 1; end; until L2 >= R2; if R2 - Left > Right - L2 then // is left side piece larger? begin if Left < R2 then Stack.Push(Left, R2); Left := L2; end; else begin if L2 < Right then // if left side isn't, right side is larger Stack.Push(L2, Right); Right := R2; end; until Left >= Right; end; end;

ALGOL 68
Quick sort in ALGOL 68 using the PAR clause to break the job into multiple threads.

AppleScript
This is a basic implementation using C.A.R. Hoare's algorithm with pivot in middle (sometimes referred to as binary or dichotomic sort). The use of a script object to store the list makes this version about 10 times faster than previously proposed one (for a list of a 1000 strings). Also "left" and "right" are keywords, and may not always run as expected. Improvement can also be done depending on data to be sorted by choosing pivot randomly or by increasing their umbers.

This is a straightforward implementation. It is certainly possible to come up with a more efficient one, but it will probably not be as clear as this one:

ARM Assembly
This ARM RISC assembly language implementation for sorting an array of 32-bit integers demonstrates how well quicksort takes advantage of the register model and capabilities of a typical machine instruction set (note that this particular implementation does not meet standard calling conventions and may use more than O(log n) space):

The call produces 3 words of stack per recursive call and is able to take advantage of its knowledge of its own behavior. A more efficient implementation would sort small ranges by a more efficient method. If an implementation obeying standard calling conventions were needed, a simple wrapper could be written for the initial call to the above function that saves the appropriate registers.

AutoIt v3
This is a straightforward implementation based on the AppleScript example. It is certainly possible to come up with a more efficient one, but it will probably not be as clear as this one:

C
The implementation in the core implementations section is limited to arrays of integers. The following implementation works with any data type, given its size and a function that compares it. This is similar to what ISO/POSIX compliant C standard libraries provide:

Result: sorted_num_list={1, 2, 3, 4, 5};

Here's yet another version with various other improvements:

An alternate simple C quicksort. The first C implementation above does not sort the list properly if the initial input is a reverse sorted list, or any time in which the pivot turns out be the largest element in the list. Here is another sample quick sort implementation that does address these issues. Note that the swaps are done inline in this implementation. They may be replaced with a swap function as in the above examples.

This sorts an array of integers using quicksort with in-place partition.

The following sample of C code can be compiled to sort a vector of strings (defined as char *list[ ]), integers, doubles, etc. This piece of code implements a mixed iterative-recursive strategy that avoids out of stack risks even in worst case. It runs faster than the standard C lib function qsort, especially when used with partially sorted arrays (compiled with free Borland bcc32 and tested with 1 million strings vector).

Iterative Quicksort
Quicksort could also be implemented iteratively with the help of a little stack. Here a simple version with random selection of the pivot element:

The pseudorandom selection of the pivot element ensures efficient sorting in O(n log n) under all input conditions (increasing, decreasing order, equal elements). The size of the needed stack is smaller than 2·log2(n) entries (about 99.9% probability). If a limited stack overflows the sorting simply restarts.

C++
This is a generic, STL-based version of quicksort.

Note that this implementation uses last iterator content, and is not suitable for a std::[whatever]sort replacement as is.

Here's a shorter version than the one in the core implementations section which takes advantage of the standard library's partition function:

C#
The followings C# implementations uses the functional aspect of c#

Faster cause uses partition

The following example uses linq to filter the list

The following C# implementation uses a random pivot.

D
Based on the C code posted at rossetacode.org

Delphi
This example sorts strings using quicksort.

Note: This can be considered bad code, as it is very slow.

This implementation sorts an array of integers.

This slightly modified implementation sorts an array of records. This is approximately 8x quicker than the previous one. Note: this is QuickSort only, more speedup can be gain with handling trivial case (comparing two values), or implementing Bubble or Shell sort on small ranges.

Elixir
The following Elixir code sorts collections that implement the Enumerbale protocol of items of any type that can be compared using the < operator.

Erlang
The following Erlang code sorts lists of items of any type.

Haskell
The Haskell code in the core implementations section 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. The following implementation does not have the aforementioned inefficiency, as it uses a partition function that ensures that we only traverse `xs' once:

Another version:

An even shorter version:

A rather fast version which builds the list from the end, making the use of (++) ok, it only traverses the list of lower parts, prepending them to head of the higher and equal lists. One draw back is that it requires the whole list be sorted, it's not very good for laziness:

qsort xs = qsort' xs [] qsort' [] end = end qsort' (x:xs) end = qsort' lower (equal ++ qsort' higher end) where (lower, equal, higher) = partit x xs ([],[x],[]) partit s [] part = part partit s (x:xs) (l,e,h) |x < s = partit s xs (x:l, e, h)       |x > s = partit s xs (l, e, x:h) |otherwise = partit s xs (l, x:e, h)

J
The J example in the core implementations section is extremely terse and difficult to understand. This implementation, from the J Dictionary, is less obtuse:

sel=: adverb def 'x. # [' quicksort=: verb define if. 1 >: #y. do. y. else. (quicksort y. sel e=.y.{~?#y. end. )

Java
The following example uses the functional characteristics of Java 8

Here is a sample Java implementation that sorts an ArrayList of numbers.

The following Java implementation uses a randomly selected pivot. Analogously to the Erlang solution above, a user-supplied determines the partial ordering of array elements:

With the advent of J2SE 5.0 you can use parameterized types to avoid passing the  used above.

Another implementation.

Here is a sample that uses recursion, like the Groovy implementation:

JavaScript
Here is another JavaScript implementation using declarative programming that does not mutate the input.

Mathematica
Here's a functional-style implementation: Here's a test driver which should yield :

Perl
Or:

Or:

PHP
With array_filter and consecutive numerical keys

Here is an in-place algorythm that performs better than the implementations above. Of course in real life use sort PHP native function.

Prolog
The version in the core implementations section is concise and, because it uses tail recursion, efficient. Here's another version:

Python
Using list comprehensions:

With in place partitioning and random pivot selection:

The above takes longer than the in place sort below, which only swaps values above the pivot value to the left, with values below the pivot to the right, instead of the previous, which re-swaps already swapped under pivot values, which doubles the number of swaps.

However, both in-place sorts are slower than the memory consuming list comprehension version, which itself is 10 times slower than the in-built sorted function.

The version below doesn't avoid the bad sorted input problem, by choosing a random pivot element or median-of-three pivot element.

Ruby
Using Closures:

Using Closures but with a random pivot:

Scala
Or shorter version:

Scheme
This uses SRFI 1 and SRFI 8. It avoids redundantly traversing the list: it partitions it with the pivot in one traversal, not two, and it avoids copying entire lists to append them, by instead only adding elements on the front of the output list's tail.

Shell
While many of the other scripting languages (e.g. Perl, Python, Ruby) have a built-in library sort routine, POSIX shells generally do not.

The following was adapted from the Applescript code above and used in the bash debugger. It has been tested on bash, zsh, and the Korn shell.

Standard ML
The following example&mdash;though less general than the snippet in the core implementations section in that it does not accept a predicate argument&mdash;strives to more closely resemble the implementations in the other functional languages. The use of  in both examples enables the implementation to walk the list only once per call, thereby reducing the constant factor of the algorithm.

Replacing the predicate is trivial:

A cleaner version that sacrifices the efficiency of  and resembles the list-comprehension versions in other functional languages:

Visual Basic
Another implementation:

To generalize it, simply change types to Variant.

Zilog Z80000 Assembly
This implementation is in z80 assembly code. The processor is really ancient, and so it's basically a register-stack recursion juggling feat. More on it and the author's comments here. It takes the register pairs BC and HL which point to the start and end memory locations to the list of one-byte elements to be sorted. All registers are filled with "garbage" data in the process, so they need to be pushed to the stack to be saved. The script is about 44 bytes long, and does not have pivot-optimizing code.

TorqueScript
This is an implementation of Quicksort using script from the Torque game Builder (aka TorqueScript).

FORTRAN 90/95
This implementation of quicksort in FORTRAN 90/95 is non-recursive, and choose as pivot element the median of three (the first, last and middle element of the list). It also uses insertion sort to sort lists with less than 10 elements.

This implementation of Quicksort closely follows the one that can be found in the FORTRAN 90/95 GPL library AFNL.

Pascal
Another procedure with extracted partition function

Примеры реализации быстрой сортировки