All Topics  
Sorting algorithm

 

   Email Print
   Bookmark   Link






 

Sorting algorithm



 
 
In computer science
Computer science

Computer science is the study of the theoretical foundations of information and computation, and of practical techniques for their implementation and application in computer systems....
 and mathematics
Mathematics

Mathematics is the study of quantity, structure, space, change, and related topics of pattern and form. Mathematicians seek out patterns whether found in numbers, space, natural science, computers, imaginary abstractions, or elsewhere....
, a sorting algorithm is an algorithm
Algorithm

In mathematics, computing, linguistics and related subjects, an algorithm is a sequence of finite instructions, often used for calculation and data processing....
 that puts elements of a list
List (computing)

In computer science, a list is an ordered Multiset of entity/items.In the context of object-oriented programming languages, a list is defined as an instance of an abstract data type , formalizing the concept of an order theoryed Collection class of entity....
 in a certain order
Total order

In mathematics and set theory, a total order, linear order, simple order, or ordering is a binary relation on some Set X....
. The most-used orders are numerical order and lexicographical order
Lexicographical order

In mathematics, the lexicographic or lexicographical order, , is a natural order theory structure of the Cartesian product of two ordered sets....
. Efficient sorting
Sorting

Sorting is any process of arranging items in some sequence and/or in different sets, and accordingly, it has two common, yet distinct meanings:...
 is important to optimizing the use of other algorithms (such as search
Search algorithm

In computer science, a search algorithm, broadly speaking, is an algorithm that takes a problem as input and returns a solution to the problem, usually after evaluating a number of possible solutions....
 and merge
Merge algorithm

Merge algorithms are a family of algorithms that run sequentially over multiple sorting algorithm lists, typically producing more sorted lists as output....
 algorithms) that require sorted lists to work correctly; it is also often useful for canonicalizing
Canonicalization

In computer science, canonicalization is a process for converting data that has more than one possible representation into a "standard" canonical representation....
 data and for producing human-readable output. More formally, the output must satisfy two conditions:

  1. The output is in nondecreasing order (each element is no smaller than the previous element according to the desired total order
    Total order

    In mathematics and set theory, a total order, linear order, simple order, or ordering is a binary relation on some Set X....
    );
  2. The output is a permutation
    Permutation

    In several fields of mathematics the term permutation is used with different but closely related meanings. They all relate to the notion of mapping the element s of a set to other elements of the same set, i.e., exchanging elements of a set....
    , or reordering, of the input.


Since the dawn of computing, the sorting problem has attracted a great deal of research, perhaps due to the complexity of solving it efficiently despite its simple, familiar statement.






Discussion
Ask a question about 'Sorting algorithm'
Start a new discussion about 'Sorting algorithm'
Answer questions from other users
Full Discussion Forum



Encyclopedia


In computer science
Computer science

Computer science is the study of the theoretical foundations of information and computation, and of practical techniques for their implementation and application in computer systems....
 and mathematics
Mathematics

Mathematics is the study of quantity, structure, space, change, and related topics of pattern and form. Mathematicians seek out patterns whether found in numbers, space, natural science, computers, imaginary abstractions, or elsewhere....
, a sorting algorithm is an algorithm
Algorithm

In mathematics, computing, linguistics and related subjects, an algorithm is a sequence of finite instructions, often used for calculation and data processing....
 that puts elements of a list
List (computing)

In computer science, a list is an ordered Multiset of entity/items.In the context of object-oriented programming languages, a list is defined as an instance of an abstract data type , formalizing the concept of an order theoryed Collection class of entity....
 in a certain order
Total order

In mathematics and set theory, a total order, linear order, simple order, or ordering is a binary relation on some Set X....
. The most-used orders are numerical order and lexicographical order
Lexicographical order

In mathematics, the lexicographic or lexicographical order, , is a natural order theory structure of the Cartesian product of two ordered sets....
. Efficient sorting
Sorting

Sorting is any process of arranging items in some sequence and/or in different sets, and accordingly, it has two common, yet distinct meanings:...
 is important to optimizing the use of other algorithms (such as search
Search algorithm

In computer science, a search algorithm, broadly speaking, is an algorithm that takes a problem as input and returns a solution to the problem, usually after evaluating a number of possible solutions....
 and merge
Merge algorithm

Merge algorithms are a family of algorithms that run sequentially over multiple sorting algorithm lists, typically producing more sorted lists as output....
 algorithms) that require sorted lists to work correctly; it is also often useful for canonicalizing
Canonicalization

In computer science, canonicalization is a process for converting data that has more than one possible representation into a "standard" canonical representation....
 data and for producing human-readable output. More formally, the output must satisfy two conditions:

  1. The output is in nondecreasing order (each element is no smaller than the previous element according to the desired total order
    Total order

    In mathematics and set theory, a total order, linear order, simple order, or ordering is a binary relation on some Set X....
    );
  2. The output is a permutation
    Permutation

    In several fields of mathematics the term permutation is used with different but closely related meanings. They all relate to the notion of mapping the element s of a set to other elements of the same set, i.e., exchanging elements of a set....
    , or reordering, of the input.


Since the dawn of computing, the sorting problem has attracted a great deal of research, perhaps due to the complexity of solving it efficiently despite its simple, familiar statement. For example, bubble sort
Bubble sort

Bubble sort is a simple sorting algorithm. It works by repeatedly stepping through the list to be sorted, comparing two items at a time and swapping them if they are in the wrong order....
 was analyzed as early as 1956. Although many consider it a solved problem, useful new sorting algorithms are still being invented (for example, library sort
Library sort

Library sort, or gapped insertion sort is a sorting algorithm that uses an insertion sort, but with gaps in the array to accelerate subsequent insertions....
 was first published in 2004). Sorting algorithms are prevalent in introductory computer science classes, where the abundance of algorithms for the problem provides a gentle introduction to a variety of core algorithm concepts, such as big O notation
Big O notation

In mathematics, big O notation describes the asymptotic analysis of a function when the argument tends towards a particular value or infinity, usually in terms of simpler functions....
, divide and conquer algorithm
Divide and conquer algorithm

In computer science, divide and conquer is an important algorithm design paradigm based on multi-branched recursion. A divide and conquer algorithm works by recursively breaking down a problem into two or more sub-problems of the same type, until these become simple enough to be solved directly....
s, data structure
Data structure

A data structure in computer science is a way of storing data in a computer so that it can be used efficiently. It is an organization of mathematical and logical concepts of data....
s, randomized algorithm
Randomized algorithm

A randomized algorithm or probabilistic algorithm is an algorithm which employs a degree of randomness as part of its logic. The algorithm typically uses Uniform distribution bits as an auxiliary input to guide its behavior, in the hope of achieving good performance in the "average case" over all possible choices of random bits....
s, best, worst and average case
Best, worst and average case

In computer science, best, worst and average cases of a given algorithm express what the Resource usage is at least, at most and on average, respectively....
 analysis, time-space tradeoffs, and lower bounds.

Classification

Sorting algorithms used in computer science
Computer science

Computer science is the study of the theoretical foundations of information and computation, and of practical techniques for their implementation and application in computer systems....
 are often classified by:

  • Computational complexity
    Computational complexity theory

    Computational complexity theory, as a branch of the theory of computation in computer science, investigates the problems related to the Computational resource required for the execution of algorithms , and the inherent difficulty in providing efficient algorithms for specific computational problems....
     (worst, average and best behaviour) of element comparisons in terms of the size of the list . For typical sorting algorithms good behavior is
    Big O notation

    In mathematics, big O notation describes the asymptotic analysis of a function when the argument tends towards a particular value or infinity, usually in terms of simpler functions....
     and bad behavior is . (See Big O notation
    Big O notation

    In mathematics, big O notation describes the asymptotic analysis of a function when the argument tends towards a particular value or infinity, usually in terms of simpler functions....
    ) Ideal behavior for a sort is . Comparison sort
    Comparison sort

    A comparison sort is a type of sorting algorithm that only reads the list elements through a single abstract comparison operation that determines which of two elements should occur first in the final sorted list....
    s, sort algorithms which only access the list via an abstract key comparison operation, always need comparisons in the worst case.
  • Computational complexity
    Computational complexity theory

    Computational complexity theory, as a branch of the theory of computation in computer science, investigates the problems related to the Computational resource required for the execution of algorithms , and the inherent difficulty in providing efficient algorithms for specific computational problems....
     of swaps (for "in place" algorithms).
  • Memory usage (and use of other computer resources). In particular, some sorting algorithms are "in place
    In-place algorithm

    In computer science, an in-place algorithm is an algorithm which transforms a data structure using a small, constant amount of extra storage space....
    ". This means that they need only or memory beyond the items being sorted and they don't need to create auxiliary locations for data to be temporarily stored, as in other sorting algorithms.
  • Recursion. Some algorithms are either recursive or non recursive, while others may be both (e.g., merge sort).
  • Stability: stable sorting algorithms maintain the relative order of records with equal keys (i.e., values). See below for more information.
  • Whether or not they are a comparison sort
    Comparison sort

    A comparison sort is a type of sorting algorithm that only reads the list elements through a single abstract comparison operation that determines which of two elements should occur first in the final sorted list....
    . A comparison sort examines the data only by comparing two elements with a comparison operator.
  • General method: insertion, exchange, selection, merging, etc. Exchange sorts include bubble sort and quicksort. Selection sorts include shaker sort and heapsort.
  • Adaptability: Whether or not the presortedness of the input affects the running time. Algorithms that take this into account are known to be adaptive
    Adaptive sort

    A sorting algorithm falls into the adaptive sort family if it takes advantage of existing order in its input. It benefits from the presortedness in the input sequence ? or a limited amount of randomness for various definitions of measures of disorder ? and sorts faster....
    .


Stability
Stable sorting algorithms maintain the relative order of records with equal keys. If all keys are different then this distinction does not make any sense. But if there are equal keys, then a sorting algorithm is stable if whenever there are two records(let's say R and S) with the same key, and R appears before S in the original list, then R will always appear before S in the sorted list. When equal elements are indistinguishable, such as with integers, or more generally, any data where the entire element is the key, stability is not an issue. However, assume that the following pairs of numbers are to be sorted by their first component:

(4, 2) (3, 7) (3, 1) (5, 6)

In this case, two different results are possible, one which maintains the relative order of records with equal keys, and one which does not:

(3, 7) (3, 1) (4, 2) (5, 6) (order maintained) (3, 1) (3, 7) (4, 2) (5, 6) (order changed)

Unstable sorting algorithms may change the relative order of records with equal keys, but stable sorting algorithms never do so. Unstable sorting algorithms can be specially implemented to be stable. One way of doing this is to artificially extend the key comparison, so that comparisons between two objects with otherwise equal keys are decided using the order of the entries in the original data order as a tie-breaker. Remembering this order, however, often involves an additional computational cost
Computational complexity theory

Computational complexity theory, as a branch of the theory of computation in computer science, investigates the problems related to the Computational resource required for the execution of algorithms , and the inherent difficulty in providing efficient algorithms for specific computational problems....
.

Sorting based on a primary, secondary, tertiary, etc. sort key can be done by any sorting method, taking all sort keys into account in comparisons (in other words, using a single composite sort key). If a sorting method is stable, it is also possible to sort multiple times, each time with one sort key. In that case the keys need to be applied in order of increasing priority.

Example: sorting pairs of numbers as above by first, then second component:

(4, 2) (3, 7) (3, 1) (4, 6) (original)

(3, 1) (4, 2) (4, 6) (3, 7) (after sorting by second component) (3, 1) (3, 7) (4, 2) (4, 6) (after sorting by first component)

On the other hand:

(3, 7) (3, 1) (4, 2) (4, 6) (after sorting by first component) (3, 1) (4, 2) (4, 6) (3, 7) (after sorting by second component, order by first component is disrupted).

List of sorting algorithms

In this table, n is the number of records to be sorted. The columns "Average" and "Worst" give the time complexity in each case, under the assumption that the length of each key is constant, and that therefore all comparisons, swaps, and other needed operations can proceed in constant time. "Memory" denotes the amount of auxiliary storage needed beyond that used by the list itself, under the same assumption. These are all comparison sort
Comparison sort

A comparison sort is a type of sorting algorithm that only reads the list elements through a single abstract comparison operation that determines which of two elements should occur first in the final sorted list....
s.

Name Average Worst Memory Stable Method Other notes
Bubble sort
Bubble sort

Bubble sort is a simple sorting algorithm. It works by repeatedly stepping through the list to be sorted, comparing two items at a time and swapping them if they are in the wrong order....
Yes Exchanging
Cocktail sort
Cocktail sort

Cocktail sort, also known as bidirectional bubble sort, cocktail shaker sort, shaker sort , ripple sort, shuttle sort or happy hour sort, is a variation of bubble sort that is both a stable sort sorting algorithm and a comparison sort....
Yes Exchanging
Comb sort
Comb sort

In computer science, comb sort is a relatively simplistic sorting algorithm originally designed by Wlodek Dobosiewicz in 1980 and later rediscovered and popularised by Stephen Lacey and Richard Box, who described it in Byte Magazine in April 1991....
No ExchangingSmall code size
Gnome sort
Gnome sort

Gnome sort is a sorting algorithm which is similar to insertion sort, except that moving an element to its proper place is accomplished by a series of swaps, as in bubble sort....
Yes Exchanging Tiny code size
Selection sort
Selection sort

Selection sort is a sorting algorithm, specifically an in-place algorithm comparison sort. It has Big O notation complexity, making it inefficient on large lists, and generally performs worse than the similar insertion sort....
No Selection Can be implemented as a stable sort
Insertion sort
Insertion sort

Insertion sort is a simple sorting algorithm, a comparison sort in which the sorted array is built one entry at a time. It is much less efficient on large lists than more advanced algorithms such as quicksort, heapsort, or merge sort....
Yes Insertion Average case is also , where d is the number of inversions
Shell sort
Shell sort

Shell sort is a sorting algorithm that is a generalization of insertion sort, with two observations:*insertion sort is efficient if the input is "almost sorted", and...
No Insertion
Binary tree sort Yes Insertion When using a self-balancing binary search tree
Self-balancing binary search tree

In computer science, a self-balancing binary search tree or height-balanced binary search tree is a binary search tree that attempts to keep its height, or the number of levels of nodes beneath the root, as small as possible at all times, automatically....
Library sort
Library sort

Library sort, or gapped insertion sort is a sorting algorithm that uses an insertion sort, but with gaps in the array to accelerate subsequent insertions....
Yes Insertion
Merge sort
Merge sort

Merge sort or merge_sort is an Big O notation comparison sort sorting algorithm. In most implementations it is Sorting algorithm#Classification, meaning that it preserves the input order of equal elements in the sorted output....
Yes Merging
In-place merge sort
Merge sort

Merge sort or merge_sort is an Big O notation comparison sort sorting algorithm. In most implementations it is Sorting algorithm#Classification, meaning that it preserves the input order of equal elements in the sorted output....
No Merging Example implementation here: ; can be implemented as a stable sort based on stable in-place merging:
Heapsort
Heapsort

Heapsort is a comparison sort sorting algorithm, and is part of the selection sort family. Although somewhat slower in practice on most machines than a good implementation of quicksort, it has the advantage of a worst-case big O notation runtime....
No Selection
Smoothsort No Selection
Quicksort
Quicksort

Quicksort is a well-known sorting algorithm developed by C. A. R. Hoare that, average performance, makes comparisons to sort n items. However, in the Best, worst and average case, it makes comparisons....
No Partitioning Naïve
Naïve algorithm

A na?ve algorithm is typically a very simple solution to a problem, which represents the intuitive approach taken by one unfamiliar with the problem domain....
 variants use space; can be worst case if median pivot is used
Introsort
Introsort

Introsort or introspective sort is a sorting algorithm designed by David Musser in 1997. It begins with quicksort and switches to heapsort when the recursion depth exceeds a level based on the number of elements being sorted....
No Hybrid Used in SGI
Silicon Graphics

Silicon Graphics, Inc. is a company manufacturer high-performance computing solutions, including computer hardware and computer software. SGI was founded by James H....
 STL
Standard Template Library

The Standard Template Library is a Library partially included in the C++ C++ standard library. It provides Container s, iterators, algorithms, and Function objects....
 implementations
Patience sorting
Patience sorting

Patience sorting is a sorting algorithm, based on a solitaire card game, that has the property of being able to efficiently compute the length of the longest increasing subsequence in a given array....
No Insertion & Selection Finds all the longest increasing subsequence
Longest increasing subsequence

The longest increasing subsequence problem is to find a subsequence of a given sequence in which the subsequence elements are in sorted order, lowest to highest, and in which the subsequence is as long as possible....
s within O(n log n)
Strand sort
Strand sort

Strand sort is a sorting algorithm. It works by repeatedly pulling sorted sublists out of the list to be sorted and merging them with a result array....
Yes Selection 


The following table describes sorting algorithms that are not comparison sort
Comparison sort

A comparison sort is a type of sorting algorithm that only reads the list elements through a single abstract comparison operation that determines which of two elements should occur first in the final sorted list....
s. As such, they are not limited by a lower bound. Complexities below are in terms of n, the number of items to be sorted, k, the size of each key, and s, the chunk size used by the implementation. Many of them are based on the assumption that the key size is large enough that all entries have unique key values, and hence that n << 2k, where << means "much less than."

Name Average Worst Memory Stable n << 2k Notes
Pigeonhole sort
Pigeonhole sort

Pigeonhole sorting, also known as count sort , is a sorting algorithm that is suitable for sorting lists of elements where the number of elements and the number of possible key values are approximately the same....
    Yes Yes
Bucket sort
Bucket sort

Bucket sort, or bin sort, is a sorting algorithm that works by partitioning an array into a number of bucket s. Each bucket is then sorted individually, either using a different sorting algorithm, or by recursively applying the bucket sorting algorithm....
    Yes No Assumes uniform distribution of elements from the domain in the array.
Counting sort
Counting sort

Counting sort is a sorting algorithm which takes advantage of knowing the Range of the numbers in the array to be sorted . It uses this range to create an array C of this length....
    Yes Yes
LSD Radix sort
Radix sort

In computer science, radix sort is a sorting algorithm created by Dr. Ian P. Turnipseed that sorts integers by processing individual digits. Because integers can represent strings of characters and specially formatted floating point numbers, radix sort is not limited to integers....
    Yes No
MSD Radix sort
Radix sort

In computer science, radix sort is a sorting algorithm created by Dr. Ian P. Turnipseed that sorts integers by processing individual digits. Because integers can represent strings of characters and specially formatted floating point numbers, radix sort is not limited to integers....
    No No
Spreadsort
Spreadsort

Spreadsort is a sorting algorithm invented by Steven J. Ross in 2002. It combines concepts from distribution-based sorts, such as radix sort and bucket sort, with partitioning concepts from comparison sorts such as quicksort and mergesort....
    No No Asymptotics are based on the assumption that n << 2k, but the algorithm does not require this.


The following table describes some sorting algorithms that are impractical for real-life use due to extremely poor performance or a requirement for specialized hardware.

Name Average Worst Memory Stable Comparison Other notes
Bogosort
Bogosort

In computer science, bogosort is a particularly ineffective sorting algorithm. Its only use is for educational purposes, to contrast it with other more realistic algorithms....
 Unbounded   No Yes Average time using Fisher-Yates shuffle
Fisher-Yates shuffle

The Fisher-Yates shuffle, named after Ronald Fisher and Frank Yates, also known as the Knuth shuffle, after Donald Knuth, is an algorithm for generating a random permutation of a finite set?in plain terms, for randomly shuffling the set....
Bozo sort
Bogosort

In computer science, bogosort is a particularly ineffective sorting algorithm. Its only use is for educational purposes, to contrast it with other more realistic algorithms....
 Unbounded   No Yes Average time is asymptotically half that of bogosort
Stooge sort
Stooge sort

Stooge sort is a Recursion sorting algorithm with a time complexity of about O.The exponent's exact value is log / log = 2.709... The running time of the algorithm is thus extremely slow compared...
    No Yes
Bead sort
Bead sort

Bead sort is a natural algorithm sorting algorithm, developed by Joshua J. Arulanandham, Cristian S. Calude and Michael J. Dinneen in 2002, and published in The Bulletin of the European Association for Theoretical Computer Science....
N/A N/A N/A No Requires specialized hardware
Simple pancake sort
Pancake sorting

Pancake sorting is a variation of the sorting algorithm problem in which the only allowed operation is to reverse the elements of some prefix of the sequence....
No Yes Count is number of flips.
Sorting network
Sorting network

A sorting network is an abstract mathematical model of a network of wires and comparator modules that is used to sort a sequence of numbers. Each comparator connects two wires and sort the values by outputting the smaller value to one wire, and a larger value to the other....
s
  Yes No Requires a custom circuit of size


Additionally, theoretical computer scientists have detailed other sorting algorithms that provide better than time complexity with additional constraints, including:

  • Han's algorithm, a deterministic algorithm for sorting keys from a domain
    Domain

    Domain has several meanings:...
     of finite size, taking time and space.
  • Thorup's algorithm, a randomized algorithm for sorting keys from a domain of finite size, taking time and space.
  • An integer
    Integer

    The integers are natural numbers including 0 and their negative and non-negative numberss . They are numbers that can be written without a fractional or decimal component, and fall within the set ....
     sorting algorithm taking time and space.


While theoretically interesting, to date these algorithms have seen little use in practice.

Summaries of popular sorting algorithms


Bubble sort

Bubble sort is a straightforward and simplistic method of sorting data that is used in computer science education. The algorithm starts at the beginning of the data set. It compares the first two elements, and if the first is greater than the second, it swaps them. It continues doing this for each pair of adjacent elements to the end of the data set. It then starts again with the first two elements, repeating until no swaps have occurred on the last pass. While simple, this algorithm is highly inefficient and is rarely used except in education. For example, if we have 100 elements then the total number of comparisons will be 10000. A slightly better variant, cocktail sort
Cocktail sort

Cocktail sort, also known as bidirectional bubble sort, cocktail shaker sort, shaker sort , ripple sort, shuttle sort or happy hour sort, is a variation of bubble sort that is both a stable sort sorting algorithm and a comparison sort....
, works by inverting the ordering criteria and the pass direction on alternating passes. Its average case and worst case are both O(n²).

Insertion sort

Insertion sort is a simple sorting algorithm that is relatively efficient for small lists and mostly-sorted lists, and often is used as part of more sophisticated algorithms. It works by taking elements from the list one by one and inserting them in their correct position into a new sorted list. In arrays, the new list and the remaining elements can share the array's space, but insertion is expensive, requiring shifting all following elements over by one. Shell sort
Shell sort

Shell sort is a sorting algorithm that is a generalization of insertion sort, with two observations:*insertion sort is efficient if the input is "almost sorted", and...
 (see below) is a variant of insertion sort that is more efficient for larger lists.

Shell sort

Shell sort was invented by Donald Shell
Donald Shell

Donald L. Shell is a retired United States computer science who designed the Shell sort sorting algorithm. He acquired his Ph.D. in Mathematics from the University of Cincinnati in 1959, after publishing the shell sort algorithm in the Communications of the ACM in July the same year....
 in 1959. It improves upon bubble sort and insertion sort by moving out of order elements more than one position at a time. One implementation can be described as arranging the data sequence in a two-dimensional array and then sorting the columns of the array using insertion sort. Although this method is inefficient for large data sets, it is one of the fastest algorithms for sorting small numbers of elements (sets with fewer than 1000 or so elements). Another advantage of this algorithm is that it requires relatively small amounts of memory.

Merge sort

Merge sort takes advantage of the ease of merging already sorted lists into a new sorted list. It starts by comparing every two elements (i.e., 1 with 2, then 3 with 4...) and swapping them if the first should come after the second. It then merges each of the resulting lists of two into lists of four, then merges those lists of four, and so on; until at last two lists are merged into the final sorted list. Of the algorithms described here, this is the first that scales well to very large lists, because its worst-case running time is O(n log n).

Heapsort

Heapsort is a much more efficient version of selection sort
Selection sort

Selection sort is a sorting algorithm, specifically an in-place algorithm comparison sort. It has Big O notation complexity, making it inefficient on large lists, and generally performs worse than the similar insertion sort....
. It also works by determining the largest (or smallest) element of the list, placing that at the end (or beginning) of the list, then continuing with the rest of the list, but accomplishes this task efficiently by using a data structure called a heap
Heap (data structure)

In computer science, a heap is a specialized tree data structure-based data structure that satisfies the heap property: if B is a child node of A, then key ≥ key....
, a special type of binary tree
Binary tree

In computer science, a binary tree is a Tree in which each node has at most two child node. Typically the child nodes are called left and right....
. Once the data list has been made into a heap, the root node is guaranteed to be the largest element. When it is removed and placed at the end of the list, the heap is rearranged so the largest element remaining moves to the root. Using the heap, finding the next largest element takes O(log n) time, instead of O(n) for a linear scan as in simple selection sort. This allows Heapsort to run in O(n log n) time.

Quicksort

Quicksort is a divide and conquer
Divide and conquer algorithm

In computer science, divide and conquer is an important algorithm design paradigm based on multi-branched recursion. A divide and conquer algorithm works by recursively breaking down a problem into two or more sub-problems of the same type, until these become simple enough to be solved directly....
 algorithm
Algorithm

In mathematics, computing, linguistics and related subjects, an algorithm is a sequence of finite instructions, often used for calculation and data processing....
 which relies on a partition operation: to partition an array, we choose an element, called a pivot, move all smaller elements before the pivot, and move all greater elements after it. This can be done efficiently in linear time and in-place
In-place algorithm

In computer science, an in-place algorithm is an algorithm which transforms a data structure using a small, constant amount of extra storage space....
. We then recursively sort the lesser and greater sublists. Efficient implementations of quicksort (with in-place partitioning) are typically unstable sorts and somewhat complex, but are among the fastest sorting algorithms in practice. Together with its modest O(log n) space usage, this makes quicksort one of the most popular sorting algorithms, available in many standard libraries. The most complex issue in quicksort is choosing a good pivot element; consistently poor choices of pivots can result in drastically slower O(n²) performance, but if at each step we choose the median as the pivot then it works in O(n log n).

Bucket sort

Bucket sort is a sorting algorithm that works by partitioning an array into a finite number of buckets. Each bucket is then sorted individually, either using a different sorting algorithm, or by recursively applying the bucket sorting algorithm. A variation of this method called the single buffered count sort is faster than the quicksort and takes about the same time to run on any set of data.

Radix sort

Radix sort is an algorithm that sorts a list of fixed-size numbers of length k in O(n · k) time by treating them as bit strings. We first sort the list by the least significant bit while preserving their relative order using a stable sort. Then we sort them by the next bit, and so on from right to left, and the list will end up sorted. Most often, the counting sort
Counting sort

Counting sort is a sorting algorithm which takes advantage of knowing the Range of the numbers in the array to be sorted . It uses this range to create an array C of this length....
 algorithm is used to accomplish the bitwise sorting, since the number of values a bit can have is small.

Distribution sort

Distribution sort refers to any sorting algorithm where data is distributed from its input to multiple intermediate structures which are then gathered and placed on the output. It is typically not considered to be very efficient because the intermediate structures need to be created, but sorting in smaller groups is more efficient than sorting one larger group.

Shuffle sort

Shuffle sort is a type of distribution sort algorithm (see above) that begins by removing the first 1/8 of the n items to be sorted, sorts them recursively, and puts them in an array. This creates n/8 "buckets" to which the remaining 7/8 of the items are distributed. Each "bucket" is then sorted, and the "buckets" are concatenated into a sorted array.

Memory usage patterns and index sorting

When the size of the array to be sorted approaches or exceeds the available primary memory, so that (much slower) disk or swap space must be employed, the memory usage pattern of a sorting algorithm becomes important, and an algorithm that might have been fairly efficient when the array fit easily in RAM may become impractical. In this scenario, the total number of comparisons becomes (relatively) less important, and the number of times sections of memory must be copied or swapped to and from the disk can dominate the performance characteristics of an algorithm. Thus, the number of passes and the localization of comparisons can be more important than the raw number of comparisons, since comparisons of nearby elements to one another happen at system bus
Computer bus

In computer architecture, a bus is a subsystem that transfers data between computer components inside a computer or between computers. Each bus defines its set of connectors to physically plug devices, cards or cables together....
 speed (or, with caching, even at CPU
Central processing unit

A central processing unit is an electronic circuit that can execute computer programs. This broad definition can easily be applied to many early computers that existed long before the term "CPU" ever came into widespread usage....
 speed), which, compared to disk speed, is virtually instantaneous.

For example, the popular recursive quicksort
Quicksort

Quicksort is a well-known sorting algorithm developed by C. A. R. Hoare that, average performance, makes comparisons to sort n items. However, in the Best, worst and average case, it makes comparisons....
 algorithm provides quite reasonable performance with adequate RAM, but due to the recursive way that it copies portions of the array it becomes much less practical when the array does not fit in RAM, because it may cause a number of slow copy or move operations to and from disk. In that scenario, another algorithm may be preferable even if it requires more total comparisons.

One way to work around this problem, which works well when complex records (such as in a relational database
Relational database

A relational database is a database that groups data using common attributes found in the data set. The resulting "clumps" of organized data are much easier for people to understand....
) are being sorted by a relatively small key field, is to create an index into the array and then sort the index, rather than the entire array. (A sorted version of the entire array can then be produced with one pass, reading from the index, but often even that is unnecessary, as having the sorted index is adequate.) Because the index is much smaller than the entire array, it may fit easily in memory where the entire array would not, effectively eliminating the disk-swapping problem. This procedure is sometimes called "tag sort".

Another technique for overcoming the memory-size problem is to combine two algorithms in a way that takes advantages of the strength of each to improve overall performance. For instance, the array might be subdivided into chunks of a size that will fit easily in RAM (say, a few thousand elements), the chunks sorted using an efficient algorithm (such as quicksort
Quicksort

Quicksort is a well-known sorting algorithm developed by C. A. R. Hoare that, average performance, makes comparisons to sort n items. However, in the Best, worst and average case, it makes comparisons....
 or heapsort
Heapsort

Heapsort is a comparison sort sorting algorithm, and is part of the selection sort family. Although somewhat slower in practice on most machines than a good implementation of quicksort, it has the advantage of a worst-case big O notation runtime....
), and the results merged as per mergesort. This is less efficient than just doing mergesort in the first place, but it requires less physical RAM (to be practical) than a full quicksort on the whole array.

Techniques can also be combined. For sorting very large sets of data that vastly exceed system memory, even the index may need to be sorted using an algorithm or combination of algorithms designed to perform reasonably with virtual memory
Virtual memory

Virtual memory is a computer system technique which gives an application program the impression that it has contiguous working memory , while in fact it may be physically fragmented and may even overflow on to disk storage....
, i.e., to reduce the amount of swapping required.

See also

  • External sorting
    External sorting

    External sorting is a term for a class of sorting algorithms that can handle massive amounts of data. External sorting is required when the data being sorted does not fit into the main memory of a computing device and a slower kind of memory needs to be used....
  • Sorting network
    Sorting network

    A sorting network is an abstract mathematical model of a network of wires and comparator modules that is used to sort a sequence of numbers. Each comparator connects two wires and sort the values by outputting the smaller value to one wire, and a larger value to the other....
    s (compare)
  • Collation
    Collation

    Collation is the assembly of written information into a standard order. One common type of collation is called alphabetisation, though collation is not limited to ordering letters of the alphabet....
  • Schwartzian transform
    Schwartzian transform

    In computer science, the Schwartzian Transform is a Perl programming idiom used to improve the efficiency of sorting a list of items. This idiom is appropriate for comparison-based sorting when comparing a pair of elements is a compute-intensive operation that should be performed a minimal number of times....
  • Shuffling algorithms
    Shuffle

    Shuffling is a procedure used to randomization a deck of playing cards to provide an element of chance in card games. Shuffling is often followed by a cut , to ensure that the shuffler has not manipulated the outcome....
  • Search algorithm
    Search algorithm

    In computer science, a search algorithm, broadly speaking, is an algorithm that takes a problem as input and returns a solution to the problem, usually after evaluating a number of possible solutions....
    s
  • Wikibooks: Algorithms: Uses sorting a deck of cards with many sorting algorithms as an example


External links


  • - has explanations and analyses of many of these algorithms.
  • Softpanorama page that discusses several classic algorithms and promotes alternatives to quicksort.
  • For a repository of algorithms with source code and lectures, see
  • - An interactive Java demonstration of Bubble, Insertion, Quick, Select and Merge sorts, which displays the data as a bar graph with commentary on the workings of the algorithm printed below the graph.


  • - An applet visually demonstrating a contest between a number of different sorting algorithms
  • - A method of sorting in three or more dimensions (of questionable merit)
  • - Java applet visualizing 6 different sorting algorithms
  • Pointers to
  • that explains bubble sort and quick sort and compares their performance.