Selection algorithm: Difference between revisions

Content deleted Content added
No edit summary
Undid revision 1272462687 by 49.207.232.175 (talk) the values must have an ordering. They may not be presented in that ordering.
 
(143 intermediate revisions by 34 users not shown)
Line 1:
{{Short description|Method for finding kth smallest value}}
{{for|simulated natural selection in genetic algorithms|Selection (genetic algorithm)}}
{{For|simulated natural selection in genetic algorithms|Selection (genetic algorithm)}}
{{more footnotes|date=July 2017}}
{{Good article}}
In [[computer science]], a '''selection algorithm''' is an [[algorithm]] for finding the ''k''th smallest number in a [[List (abstract data type)|list]] or [[Array data structure|array]]; such a number is called the ''k''th ''[[order statistic]]''. This includes the cases of finding the [[minimum]], [[maximum]], and [[median]] elements. There are O(''n'')-time (worst-case linear time) selection algorithms, and sublinear performance is possible for structured data; in the extreme, O(1) for an array of sorted data. Selection is a subproblem of more complex problems like the [[nearest neighbor problem|nearest neighbor]] and [[shortest path]] problems. Many selection algorithms are derived by generalizing a [[sorting algorithm]], and conversely some sorting algorithms can be derived as repeated application of selection.
{{Use mdy dates|cs1-dates=ly|date=April 2023}}
{{Use list-defined references|date=April 2023}}
In [[computer science]], a '''selection algorithm''' is an [[algorithm]] for finding the <math>k</math>th smallest value in a collection of ordered values, such as numbers. The value that it finds is called the {{nowrap|<math>k</math>th}} [[order statistic]]. Selection includes as special cases the problems of finding the [[minimum]], [[median]], and [[maximum]] element in the collection. Selection algorithms include [[quickselect]], and the [[median of medians]] algorithm. When applied to a collection of <math>n</math> values, these algorithms take [[linear time]], <math>O(n)</math> as expressed using [[big O notation]]. For data that is already structured, faster algorithms may be possible; as an extreme case, selection in an already-sorted [[Array (data structure)|array]] takes {{nowrap|time <math>O(1)</math>.}}
 
==Problem statement==
The simplest case of a selection algorithm is finding the minimum (or maximum) element by iterating through the list, keeping track of the running minimum – the minimum so far – (or maximum) and can be seen as related to the [[selection sort]]. Conversely, the hardest case of a selection algorithm is finding the median, and this necessarily takes ''n''/2 storage. In fact, a specialized median-selection algorithm can be used to build a general selection algorithm, as in [[median of medians]]. The best-known selection algorithm is [[quickselect]], which is related to [[quicksort]]; like quicksort, it has (asymptotically) optimal average performance, but poor worst-case performance, though it can be modified to give optimal worst-case performance as well.
An algorithm for the selection problem takes as input a collection of values, and a {{nowrap|number <math>k</math>.}} It outputs the {{nowrap|<math>k</math>th}} smallest of these values, or, in some versions of the problem, a collection of the <math>k</math> smallest values. For this to be well-defined, it should be possible to [[Sorting|sort]] the values into an order from smallest to largest; for instance, they may be [[Integer (computer science)|integers]], [[floating-point number]]s, or some other kind of [[Object (computer science)|object]] with a numeric key. However, they are not assumed to have been already sorted. Often, selection algorithms are restricted to a comparison-based [[model of computation]], as in [[comparison sort]] algorithms, where the algorithm has access to a [[Relational operator|comparison operation]] that can determine the relative ordering of any two values, but may not perform any other kind of [[Arithmetic|arithmetic operations]] on these values.{{r|cunmun}}
 
To simplify the problem, some works on this problem assume that the values are all distinct from each {{nowrap|other,{{r|clrs}}}} or that some consistent tie-breaking method has been used to assign an ordering to pairs of items with the same value as each other. Another variation in the problem definition concerns the numbering of the ordered values: is the smallest value obtained by {{nowrap|setting <math>k=0</math>,}} as in [[zero-based numbering]] of arrays, or is it obtained by {{nowrap|setting <math>k=1</math>,}} following the usual English-language conventions for the smallest, second-smallest, etc.? This article follows the conventions used by Cormen et al., according to which all values are distinct and the minimum value is obtained from {{nowrap|<math>k=1</math>.{{r|clrs}}}}
== Selection by sorting ==
By sorting the list or array then selecting the desired element, selection can be [[Reduction (complexity)|reduced]] to [[sorting algorithm|sorting]]. This method is inefficient for selecting a single element, but is efficient when many selections need to be made from an array, in which case only one initial, expensive sort is needed, followed by many cheap selection operations – O(1) for an array, though selection is O(''n'') in a linked list, even if sorted, due to lack of [[random access]]. In general, sorting requires O(''n'' log ''n'') time, where ''n'' is the length of the list, although a lower bound is possible with non-comparative sorting algorithms like [[radix sort]] and [[counting sort]].
 
With these conventions, the maximum value, among a collection of <math>n</math> values, is obtained by {{nowrap|setting <math>k=n</math>.}} When <math>n</math> is an [[odd number]], the [[median]] of the collection is obtained by {{nowrap|setting <math>k=(n+1)/2</math>.}} When <math>n</math> is even, there are two choices for the median, obtained by rounding this choice of <math>k</math> down or up, respectively: the ''lower median'' with <math>k=n/2</math> and the ''upper median'' with {{nowrap|<math>k=n/2+1</math>.{{r|clrs}}}}
Rather than sorting the whole list or array, one can instead use [[partial sorting]] to select the ''k'' smallest or ''k'' largest elements. The ''k''th smallest (resp., ''k''th largest element) is then the largest (resp., smallest element) of the partially sorted list – this then takes O(1) to access in an array and O(''k'') to access in a list.
 
==Algorithms==
=== Unordered partial sorting ===
===Sorting and heapselect===
If partial sorting is relaxed so that the ''k'' smallest elements are returned, but not in order, the factor of O(''k'' log ''k'') can be eliminated. An additional maximum selection (taking O(''k'') time) is required, but since <math>k \leq n</math>, this still yields asymptotic complexity of O(''n''). In fact, partition-based selection algorithms yield both the ''k''th smallest element itself and the ''k'' smallest elements (with other elements not in order). This can be done in O(''n'') time – average complexity of [[quickselect]], and worst-case complexity of refined partition-based selection algorithms.
As a baseline algorithm, selection of the {{nowrap|<math>k</math>th}} smallest value in a collection of values can be performed by the following two steps:
* [[Sorting|Sort]] the collection
* If the output of the sorting algorithm is an [[Array (data type)|array]], retrieve its {{nowrap|<math>k</math>th}} element; otherwise, scan the sorted sequence to find the {{nowrap|<math>k</math>th}} element.
The time for this method is dominated by the sorting step, which requires <math>\Theta(n\log n)</math> time using a {{nowrap|[[comparison sort]].{{r|clrs|skiena}}}} Even when [[integer sorting]] algorithms may be used, these are generally slower than the linear time that may be achieved using specialized selection algorithms. Nevertheless, the simplicity of this approach makes it attractive, especially when a highly-optimized sorting routine is provided as part of a runtime library, but a selection algorithm is not. For inputs of moderate size, sorting can be faster than non-random selection algorithms, because of the smaller constant factors in its running {{nowrap|time.{{r|erickson}}}} This method also produces a sorted version of the collection, which may be useful for other later computations, and in particular for selection with other choices {{nowrap|of <math>k</math>.{{r|skiena}}}}
 
For a sorting algorithm that generates one item at a time, such as [[selection sort]], the scan can be done in tandem with the sort, and the sort can be terminated once the {{nowrap|<math>k</math>th}} element has been found. One possible design of a consolation bracket in a [[single-elimination tournament]], in which the teams who lost to the eventual winner play another mini-tournament to determine second place, can be seen as an instance of this {{nowrap|method.{{r|bfprt}}}} Applying this optimization to [[heapsort]] produces the [[heapselect]] algorithm, which can select the {{nowrap|<math>k</math>th}} smallest value in {{nowrap|time <math>O(n+k\log n)</math>.{{r|brodal}}}} This is fast when <math>k</math> is small relative {{nowrap|to <math>n</math>,}} but degenerates to <math>O(n\log n)</math> for larger values {{nowrap|of <math>k</math>,}} such as the choice <math>k=n/2</math> used for median finding.
Conversely, given a selection algorithm, one can easily get an unordered partial sort (''k'' smallest elements, not in order) in O(''n'') time by iterating through the list and recording all elements less than the ''k''th element. If this results in fewer than ''k''&nbsp;&minus;&nbsp;1 elements, any remaining elements equal the ''k''th element. Care must be taken, due to the possibility of equality of elements: one must not include all elements less than ''or equal to'' the ''k''th element, as elements greater than the ''k''th element may also be equal to it.
 
===Pivoting===
Thus unordered partial sorting (lowest ''k'' elements, but not ordered) and selection of the ''k''th element are very similar problems. Not only do they have the same asymptotic complexity, O(''n''), but a solution to either one can be converted into a solution to the other by a straightforward algorithm (finding a max of ''k'' elements, or filtering elements of a list below a cutoff of the value of the ''k''th element).
Many methods for selection are based on choosing a special "pivot" element from the input, and using comparisons with this element to divide the remaining <math>n-1</math> input values into two subsets: the set <math>L</math> of elements less than the pivot, and the set <math>R</math> of elements greater than the pivot. The algorithm can then determine where the {{nowrap|<math>k</math>th}} smallest value is to be found, based on a comparison of <math>k</math> with the sizes of these sets. In particular, {{nowrap|if <math>k\le|L|</math>,}} the {{nowrap|<math>k</math>th}} smallest value is {{nowrap|in <math>L</math>,}} and can be found recursively by applying the same selection algorithm {{nowrap|to <math>L</math>.}} {{nowrap|If <math>k=|L|+1</math>,}} then the {{nowrap|<math>k</math>th}} smallest value is the pivot, and it can be returned immediately. In the remaining case, the {{nowrap|<math>k</math>th}} smallest value is {{nowrap|in <math>R</math>,}} and more specifically it is the element in position <math>k-|L|-1</math> {{nowrap|of <math>R</math>.}} It can be found by applying a selection algorithm recursively, seeking the value in this position {{nowrap|in <math>R</math>.{{r|kletar}}}}
 
As with the related pivoting-based [[quicksort]] algorithm, the partition of the input into <math>L</math> and <math>R</math> may be done by making new collections for these sets, or by a method that partitions a given list or array data type in-place. Details vary depending on how the input collection is {{nowrap|represented.<ref>For instance, Cormen et al. use an in-place array partition, while Kleinberg and Tardos describe the input as a set and use a method that partitions it into two new sets.</ref>}} The time to compare the pivot against all the other values {{nowrap|is <math>O(n)</math>.{{r|kletar}}}} However, pivoting methods differ in how they choose the pivot, which affects how big the subproblems in each recursive call will be. The efficiency of these methods depends greatly on the choice of the pivot. If the pivot is chosen badly, the running time of this method can be as slow {{nowrap|as <math>O(n^2)</math>.{{r|erickson}}}}
=== Partial selection sort ===
*If the pivot were exactly at the median of the input, then each recursive call would have at most half as many values as the previous call, and the total times would add in a [[geometric series]] {{nowrap|to <math>O(n)</math>.}} However, finding the median is itself a selection problem, on the entire original input. Trying to find it by a recursive call to a selection algorithm would lead to an infinite recursion, because the problem size would not decrease in each {{nowrap|call.{{r|kletar}}}}
A simple example of selection by partial sorting is to use the partial [[selection sort]].
*[[Quickselect]] chooses the pivot uniformly at random from the input values. It can be described as a [[prune and search]] algorithm,{{r|gootam}} a variant of [[quicksort]], with the same pivoting strategy, but where quicksort makes two recursive calls to sort the two subcollections <math>L</math> {{nowrap|and <math>R</math>,}} quickselect only makes one of these two calls. Its [[expected time]] {{nowrap|is <math>O(n)</math>.{{r|clrs|kletar|gootam}}}} For any constant <math>C</math>, the probability that its number of comparisons exceeds <math>Cn</math> is superexponentially small {{nowrap|in <math>C</math>.{{r|devroye}}}}
*The [[Floyd–Rivest algorithm]], a variation of quickselect, chooses a pivot by randomly sampling a subset of <math>r</math> data values, for some sample {{nowrap|size <math>r</math>,}} and then recursively selecting two elements somewhat above and below position <math>rk/n</math> of the sample to use as pivots. With this choice, it is likely that <math>k</math> is sandwiched between the two pivots, so that after pivoting only a small number of data values between the pivots are left for a recursive call. This method can achieve an expected number of comparisons that is {{nowrap|<math>n+\min(k,n-k)+o(n)</math>.{{r|floriv}}}} In their original work, Floyd and Rivest claimed that the <math>o(n)</math> term could be made as small as <math>O(\sqrt n)</math> by a recursive sampling scheme, but the correctness of their analysis has been {{nowrap|questioned.{{r|brown|prt}}}} Instead, more rigorous analysis has shown that a version of their algorithm achieves <math>O(\sqrt{n\log n})</math> for this {{nowrap|term.{{r|knuth}}}} Although the usual analysis of both quickselect and the Floyd–Rivest algorithm assumes the use of a [[true random number generator]], a version of the Floyd–Rivest algorithm using a [[pseudorandom number generator]] seeded with only logarithmically many true random bits has been proven to run in linear time with high probability.{{r|karrag}}
[[File:Mid-of-mid.png|thumb|upright=1.35|Visualization of pivot selection for the [[median of medians]] method. Each set of five elements is shown as a column of dots in the figure, sorted in increasing order from top to bottom. If their medians (the green and purple dots in the middle row) are sorted in increasing order from left to right, and the median of medians is chosen as the pivot, then the <math>3n/10</math> elements in the upper left quadrant will be less than the pivot, and the <math>3n/10</math> elements in the lower right quadrant will be greater than the pivot, showing that many elements will be eliminated by pivoting.]]
*The [[median of medians]] method partitions the input into sets of five elements, and uses some other non-recursive method to find the median of each of these sets in constant time per set. It then recursively calls itself to find the median of these <math>n/5</math> medians. Using the resulting median of medians as the pivot produces a partition with {{nowrap|<math>\max(|L|,|R|)\le 7n/10</math>.}} Thus, a problem on <math>n</math> elements is reduced to two recursive problems on <math>n/5</math> elements (to find the pivot) and at most <math>7n/10</math> elements (after the pivot is used). The total size of these two recursive subproblems is at {{nowrap|most <math>9n/10</math>,}} allowing the total time to be analyzed as a geometric series adding {{nowrap|to <math>O(n)</math>.}} Unlike quickselect, this algorithm is deterministic, not {{nowrap|randomized.{{r|clrs|erickson|bfprt}}}} It was the first linear-time deterministic selection algorithm {{nowrap|known,{{r|bfprt}}}} and is commonly taught in undergraduate algorithms classes as an example of a [[Divide-and-conquer algorithm|divide and conquer]] that does not divide into two equal {{nowrap|subproblems.{{r|clrs|erickson|gootam|gurwitz}}}} However, the high constant factors in its <math>O(n)</math> time bound make it slower than quickselect in {{nowrap|practice,{{r|skiena|gootam}}}} and slower even than sorting for inputs of moderate {{nowrap|size.{{r|erickson}}}}
*Hybrid algorithms such as [[introselect]] can be used to achieve the practical performance of quickselect with a fallback to medians of medians guaranteeing worst-case <math>O(n)</math> {{nowrap|time.{{r|musser}}}}
 
===Factories===
The obvious linear time algorithm to find the minimum (resp. maximum) – iterating over the list and keeping track of the minimum (resp. maximum) element so far – can be seen as a partial selection sort that selects the 1 smallest element. However, many other partial sorts also reduce to this algorithm for the case ''k''&nbsp;=&nbsp;1, such as a partial heap sort.
The deterministic selection algorithms with the smallest known numbers of comparisons, for values of <math>k</math> that are far from <math>1</math> {{nowrap|or <math>n</math>,}} are based on the concept of ''factories'', introduced in 1976 by [[Arnold Schönhage]], [[Mike Paterson]], and {{nowrap|[[Nick Pippenger]].{{r|spp}}}} These are methods that build [[partial order]]s of certain specified types, on small subsets of input values, by using comparisons to combine smaller partial orders. As a very simple example, one type of factory can take as input a sequence of single-element partial orders, compare pairs of elements from these orders, and produce as output a sequence of two-element totally ordered sets. The elements used as the inputs to this factory could either be input values that have not been compared with anything yet, or "waste" values produced by other factories. The goal of a factory-based algorithm is to combine together different factories, with the outputs of some factories going to the inputs of others, in order to eventually obtain a partial order in which one element (the {{nowrap|<math>k</math>th}} smallest) is larger than some <math>k-1</math> other elements and smaller than another <math>n-k</math> others. A careful design of these factories leads to an algorithm that, when applied to median-finding, uses at most <math>2.942n</math> comparisons. For other values {{nowrap|of <math>k</math>,}} the number of comparisons is {{nowrap|smaller.{{r|dz99}}}}
 
===Parallel algorithms===
More generally, a partial selection sort yields a simple selection algorithm which takes O(''kn'') time. This is asymptotically inefficient, but can be sufficiently efficient if ''k'' is small, and is easy to implement. Concretely, we simply find the minimum value and move it to the beginning, repeating on the remaining list until we have accumulated ''k'' elements, and then return the ''k''th element. Here is partial selection sort-based algorithm:
[[Parallel algorithm]]s for selection have been studied since 1975, when [[Leslie Valiant]] introduced the parallel comparison tree model for analyzing these algorithms, and proved that in this model selection using a linear number of comparisons requires <math>\Omega(\log\log n)</math> parallel steps, even for selecting the minimum or {{nowrap|maximum.{{r|valiant}}}} Researchers later found parallel algorithms for selection in <math>O(\log\log n)</math> steps, matching this {{nowrap|bound.{{r|akss|azapip}}}} In a randomized parallel comparison tree model it is possible to perform selection in a bounded number of steps and a linear number of {{nowrap|comparisons.{{r|reischuk}}}} On the more realistic [[parallel RAM]] model of computing, with exclusive read exclusive write memory access, selection can be performed in time <math>O(\log n)</math> with <math>O(n/\log n)</math> processors, which is optimal both in time and in the number of {{nowrap|processors.{{r|han}}}} With concurrent memory access, slightly faster parallel time is possible in {{nowrap|general,{{r|chr}}}} and the <math>\log n</math> term in the time bound can be replaced {{nowrap|by <math>\log k</math>.{{r|dieram}}}}
 
===Sublinear data structures===
'''function''' select(list[1..n], k)
When data is already organized into a [[data structure]], it may be possible to perform selection in an amount of time that is sublinear in the number of values. As a simple case of this, for data already sorted into an array, selecting the {{nowrap|<math>k</math>th}} element may be performed by a single array lookup, in constant {{nowrap|time.{{r|frejoh}}}} For values organized into a two-dimensional array of {{nowrap|size <math>m\times n</math>,}} with sorted rows and columns, selection may be performed in time {{nowrap|<math>O\bigl(m\log(2n/m)\bigr)</math>,}} or faster when <math>k</math> is small relative to the array {{nowrap|dimensions.{{r|frejoh|kkzz}}}} For a collection of <math>m</math> one-dimensional sorted arrays, with <math>k_i</math> items less than the selected item in the {{nowrap|<math>i</math>th}} array, the time is {{nowrap|<math display=inline>O\bigl(m+\sum_{i=1}^m\log(k_i+1)\bigr)</math>.{{r|kkzz}}}}
'''for''' i '''from''' 1 '''to''' k
minIndex = i
minValue = list[i]
'''for''' j '''from''' i+1 '''to''' n
'''if''' list[j] < minValue
minIndex = j
minValue = list[j]
swap list[i] and list[minIndex]
'''return''' list[k]
 
Selection from data in a [[binary heap]] takes {{nowrap|time <math>O(k)</math>.}} This is independent of the size <math>n</math> of the heap, and faster than the <math>O(k\log n)</math> time bound that would be obtained from {{nowrap|[[best-first search]].{{r|kkzz|frederickson}}}} This same method can be applied more generally to data organized as any kind of heap-ordered tree (a tree in which each node stores one value in which the parent of each non-root node has a smaller value than its child). This method of performing selection in a heap has been applied to problems of listing multiple solutions to combinatorial optimization problems, such as finding the [[k shortest path routing|{{mvar|k}} shortest paths]] in a weighted graph, by defining a [[State space (computer science)|state space]] of solutions in the form of an [[implicit graph|implicitly defined]] heap-ordered tree, and then applying this selection algorithm to this {{nowrap|tree.{{r|kpaths}}}} In the other direction, linear time selection algorithms have been used as a subroutine in a [[priority queue]] data structure related to the heap, improving the time for extracting its {{nowrap|<math>k</math>th}} item from <math>O(\log n)</math> to {{nowrap|<math>O(\log^* n+\log k)</math>;}} here <math>\log^* n</math> is the {{nowrap|[[iterated logarithm]].{{r|bks}}}}
== Partition-based selection ==
{{further|Quickselect}}
 
For a collection of data values undergoing dynamic insertions and deletions, the [[order statistic tree]] augments a [[self-balancing binary search tree]] structure with a constant amount of additional information per tree node, allowing insertions, deletions, and selection queries that ask for the {{nowrap|<math>k</math>th}} element in the current set to all be performed in <math>O(\log n)</math> time per {{nowrap|operation.{{r|clrs}}}} Going beyond the comparison model of computation, faster times per operation are possible for values that are small integers, on which binary arithmetic operations are {{nowrap|allowed.{{r|pattho}}}} It is not possible for a [[streaming algorithms|streaming algorithm]] with memory sublinear in both <math>n</math> and <math>k</math> to solve selection queries exactly for dynamic data, but the [[count–min sketch]] can be used to solve selection queries approximately, by finding a value whose position in the ordering of the elements (if it were added to them) would be within <math>\varepsilon n</math> steps of <math>k</math>, for a sketch whose size is within logarithmic factors of <math>1/\varepsilon</math>.{{r|cormut}}
Linear performance can be achieved by a partition-based selection algorithm, most basically [[quickselect]]. Quickselect is a variant of [[quicksort]] – in both one chooses a pivot and then partitions the data by it, but while Quicksort recurses on both sides of the partition, Quickselect only recurses on one side, namely the side on which the desired ''k''th element is. As with Quicksort, this has optimal average performance, in this case linear, but poor worst-case performance, in this case quadratic. This occurs for instance by taking the first element as the pivot and searching for the maximum element, if the data is already sorted. In practice this can be avoided by choosing a random element as pivot, which yields [[almost certain]] linear performance. Alternatively, a more careful deterministic pivot strategy can be used, such as [[median of medians]]. These are combined in the hybrid [[introselect]] algorithm (analogous to [[introsort]]), which starts with Quickselect but falls back to median of medians if progress is slow, resulting in both fast average performance and optimal worst-case performance of O(''n'').
 
== Lower bounds ==
The partition-based algorithms are generally done in place, which thus results in partially sorting the data. They can be done out of place, not changing the original data, at the cost of O(''n'') additional space.
The <math>O(n)</math> running time of the selection algorithms described above is necessary, because a selection algorithm that can handle inputs in an arbitrary order must take that much time to look at all of its inputs. If any one of its input values is not compared, that one value could be the one that should have been selected, and the algorithm can be made to produce an incorrect answer.{{r|kkzz}} Beyond this simple argument, there has been a significant amount of research on the exact number of comparisons needed for selection, both in the randomized and deterministic cases.
 
Selecting the minimum of <math>n</math> values requires <math>n-1</math> comparisons, because the <math>n-1</math> values that are not selected must each have been determined to be non-minimal, by being the largest in some comparison, and no two of these values can be largest in the same comparison. The same argument applies symmetrically to selecting the {{nowrap|maximum.{{r|knuth}}}}
=== Median selection as pivot strategy ===
{{further|Median of medians}}
A median-selection algorithm can be used to yield a general selection algorithm or sorting algorithm, by applying it as the pivot strategy in Quickselect or Quicksort; if the median-selection algorithm is asymptotically optimal (linear-time), the resulting selection or sorting algorithm is as well. In fact, an exact median is not necessary – an approximate median is sufficient. In the [[median of medians]] selection algorithm, the pivot strategy computes an approximate median and uses this as pivot, recursing on a smaller set to compute this pivot. In practice the overhead of pivot computation is significant, so these algorithms are generally not used, but this technique is of theoretical interest in relating selection and sorting algorithms.
 
The next simplest case is selecting the second-smallest. After several incorrect attempts, the first tight lower bound on this case was published in 1964 by Soviet mathematician [[Sergey Kislitsyn]]. It can be shown by observing that selecting the second-smallest also requires distinguishing the smallest value from the rest, and by considering the number <math>p</math> of comparisons involving the smallest value that an algorithm for this problem makes. Each of the <math>p</math> items that were compared to the smallest value is a candidate for second-smallest, and <math>p-1</math> of these values must be found larger than another value in a second comparison in order to rule them out as second-smallest.
In detail, given a median-selection algorithm, one can use it as a pivot strategy in Quickselect, obtaining a selection algorithm. If the median-selection algorithm is optimal, meaning O(''n''), then the resulting general selection algorithm is also optimal, again meaning linear. This is because Quickselect is a [[decrease and conquer]] algorithm, and using the median at each pivot means that at each step the search set decreases by half in size, so the overall complexity is a [[geometric series]] times the complexity of each step, and thus simply a constant times the complexity of a single step, in fact <math>2 = 1/(1-(1/2))</math> times (summing the series).
With <math>n-1</math> values being the larger in at least one comparison, and <math>p-1</math> values being the larger in at least two comparisons, there are a total of at least <math>n+p-2</math> comparisons. An [[Adversary model|adversary argument]], in which the outcome of each comparison is chosen in order to maximize <math>p</math> (subject to consistency with at least one possible ordering) rather than by the numerical values of the given items, shows that it is possible to force <math>p</math> to be {{nowrap|at least <math>\log_2 n</math>.}} Therefore, the worst-case number of comparisons needed to select the second smallest {{nowrap|is <math>n+\lceil\log_2 n\rceil-2</math>,}} the same number that would be obtained by holding a single-elimination tournament with a run-off tournament among the values that lost to the smallest value. However, the expected number of comparisons of a randomized selection algorithm can be better than this bound; for instance, selecting the second-smallest of six elements requires seven comparisons in the worst case, but may be done by a randomized algorithm with an expected number of {{nowrap|6.5 comparisons.{{r|knuth}}}}
 
More generally, selecting the {{nowrap|<math>k</math>th}} element out of <math>n</math> requires at least <math>n+\min(k,n-k)-O(1)</math> comparisons, in the average case, matching the number of comparisons of the Floyd–Rivest algorithm up to its <math>o(n)</math> term. The argument is made directly for deterministic algorithms, with a number of comparisons that is averaged over all possible [[permutation]]s of the input {{nowrap|values.{{r|cunmun}}}} By [[Yao's principle]], it also applies to the expected number of comparisons for a randomized algorithm on its worst-case {{nowrap|input.{{r|chan}}}}
Similarly, given a median-selection algorithm or general selection algorithm applied to find the median, one can use it as a pivot strategy in Quicksort, obtaining a sorting algorithm. If the selection algorithm is optimal, meaning O(''n''), then the resulting sorting algorithm is optimal, meaning O(''n'' log ''n''). The median is the best pivot for sorting, as it evenly divides the data, and thus guarantees optimal sorting, assuming the selection algorithm is optimal. A sorting analog to median of medians exists, using the pivot strategy (approximate median) in Quicksort, and similarly yields an optimal Quicksort.
 
For deterministic algorithms, it has been shown that selecting the {{nowrap|<math>k</math>th}} element requires <math>\bigl(1+H(k/n)\bigr)n+\Omega(\sqrt n)</math> comparisons, where <math display=block>H(x)=x\log_2\frac1x + (1-x)\log_2\frac1{1-x}</math> is the {{nowrap|[[binary entropy function]].{{r|benjoh}}}} The special case of median-finding has a slightly larger lower bound on the number of comparisons, {{nowrap|at least <math>(2+\varepsilon)n</math>,}} for {{nowrap|<math>\varepsilon\approx 2^{-80}</math>.{{r|dz01}}}}
== Incremental sorting by selection ==
Converse to selection by sorting, one can incrementally sort by repeated selection. Abstractly, selection only yields a single element, the ''k''th element. However, practical selection algorithms frequently involve partial sorting, or can be modified to do so. Selecting by partial sorting naturally does so, sorting the elements up to ''k'', and selecting by partitioning also sorts some elements: the pivots are sorted to the correct positions, with the ''k''th element being the final pivot, and the elements between the pivots have values between the pivot values. The difference between partition-based selection and partition-based sorting, as in quickselect versus quicksort, is that in selection one recurses on only one side of each pivot, sorting only the pivots (an average of log(''n'') pivots are used), rather than recursing on both sides of the pivot.
 
== Exact numbers of comparisons ==
This can be used to speed up subsequent selections on the same data; in the extreme, a fully sorted array allows O(1) selection. Further, compared with first doing a full sort, incrementally sorting by repeated selection [[amortized analysis|amortizes]] the sorting cost over multiple selections.
[[File:Median of 5.svg|thumb|upright=0.9|Finding the median of five values using six comparisons. Each step shows the comparisons to be performed next as yellow line segments, and a [[Hasse diagram]] of the order relations found so far (with smaller=lower and larger=higher) as blue line segments. The red elements have already been found to be greater than three others and so cannot be the median. The larger of the two elements in the final comparison is the median.]]
[[Donald Knuth|Knuth]] supplies the following triangle of numbers summarizing pairs of <math>n</math> and <math>k</math> for which the exact number of comparisons needed by an optimal selection algorithm is known. The {{nowrap|<math>n</math>th}} row of the triangle (starting with <math>n=1</math> in the top row) gives the numbers of comparisons for inputs of <math>n</math> values, and the {{nowrap|<math>k</math>th}} number within each row gives the number of comparisons needed to select the {{nowrap|<math>k</math>th}} smallest value from an input of that size. The rows are symmetric because selecting the {{nowrap|<math>k</math>th}} smallest requires exactly the same number of comparisons, in the worst case, as selecting the {{nowrap|<math>k</math>th}} {{nowrap|largest.{{r|knuth}}}}
 
{{center|0}}
For partially sorted data (up to ''k''), so long as the partially sorted data and the index ''k'' up to which the data is sorted are recorded, subsequent selections of ''j'' less than or equal to ''k'' can simply select the ''j''th element, as it is already sorted, while selections of ''j'' greater than ''k'' only need to sort the elements above the ''k''th position.
{{center|1 &nbsp;&nbsp; 1}}
{{center|2 &nbsp;&nbsp; 3 &nbsp;&nbsp; 2}}
{{center|3 &nbsp;&nbsp; 4 &nbsp;&nbsp; 4 &nbsp;&nbsp; 3}}
{{center|4 &nbsp;&nbsp; 6 &nbsp;&nbsp; 6 &nbsp;&nbsp; 6 &nbsp;&nbsp; 4}}
{{center|5 &nbsp;&nbsp; 7 &nbsp;&nbsp; 8 &nbsp;&nbsp; 8 &nbsp;&nbsp; 7 &nbsp;&nbsp; 5}}
{{center|6 &nbsp;&nbsp; 8 &nbsp; 10 &nbsp; 10 &nbsp; 10 &nbsp; 8 &nbsp;&nbsp; 6}}
{{center|7 &nbsp;&nbsp; 9 &nbsp; 11 &nbsp; 12 &nbsp; 12 &nbsp; 11 &nbsp; 9 &nbsp;&nbsp; 7}}
{{center|8 &nbsp; 11 &nbsp; 12 &nbsp; 14 &nbsp; 14 &nbsp; 14 &nbsp; 12 &nbsp; 11 &nbsp; 8}}
{{center|9 &nbsp; 12 &nbsp; 14 &nbsp; 15 &nbsp; 16 &nbsp; 16 &nbsp; 15 &nbsp; 14 &nbsp; 12 &nbsp; 9}}
 
Most, but not all, of the entries on the left half of each row can be found using the formula <math display=block>n-k+(k-1)\bigl\lceil\log_2(n+2-k)\bigr\rceil.</math> This describes the number of comparisons made by a method of Abdollah Hadian and [[Milton Sobel]], related to heapselect, that finds the smallest value using a single-elimination tournament and then repeatedly uses a smaller tournament among the values eliminated by the eventual tournament winners to find the next successive values until reaching the {{nowrap|<math>k</math>th}} smallest.{{r|knuth|hadsob}} Some of the larger entries were proven to be optimal using a computer search.{{r|knuth|gkp}}
For partitioned data, if the list of pivots is stored (for example, in a sorted list of the indices), then subsequent selections only need to select in the interval between two pivots (the nearest pivots below and above). The biggest gain is from the top-level pivots, which eliminate costly large partitions: a single pivot near the middle of the data cuts the time for future selections in half. The pivot list will grow over subsequent selections, as the data becomes more sorted, and can even be passed to a partition-based sort as the basis of a full sort.
 
== Language support ==
== Using data structures to select in sublinear time ==
Very few languages have built-in support for general selection, although many provide facilities for finding the smallest or largest element of a list. A notable exception is the [[Standard Template Library]] for [[C++]], which provides a templated <code>nth_element</code> method with a guarantee of expected linear time.{{r|skiena}}
Given an unorganized list of data, linear time (Ω(''n'')) is required to find the minimum element, because we have to examine every element (otherwise, we might miss it). If we organize the list, for example by keeping it sorted at all times, then selecting the ''k''th largest element is trivial, but then insertion requires linear time, as do other operations such as combining two lists.
 
[[Python (programming language)|Python]]'s standard library includes <code>heapq.nsmallest</code> and <code>heapq.nlargest</code> functions for returning the smallest or largest elements from a collection, in sorted order. The implementation maintains a [[binary heap]], limited to holding <math>k</math> elements, and initialized to the first <math>k</math> elements in the collection. Then, each subsequent item of the collection may replace the largest or smallest element in the heap if it is smaller or larger than this element. The algorithm's memory usage is superior to heapselect (the former only holds <math>k</math> elements in memory at a time while the latter requires manipulating the entire dataset into memory). Running time depends on data ordering. The best case is <math>O((n - k) + k\log k)</math> for already sorted data. The worst-case is <math>O(n\log k)</math> for reverse sorted data. In average cases, there are likely to be few heap updates and most input elements are processed with only a single comparison. For example, extracting the 100 largest or smallest values out of 10,000,000 random inputs makes 10,009,401 comparisons on average.{{r|python}}
The strategy to find an order statistic in [[sublinear time]] is to store the data in an organized fashion using suitable data structures that facilitate the selection. Two such data structures are tree-based structures and frequency tables.
 
Since 2017, [[Matlab]] has included <code>maxk()</code> and <code>mink()</code> functions, which return the maximal (minimal) <math>k</math> values in a vector as well as their indices. The Matlab documentation does not specify which algorithm these functions use or what their running {{nowrap|time is.{{r|matlab}}}}
When only the minimum (or maximum) is needed, a good approach is to use a [[Heap (data structure)|heap]], which is able to find the minimum (or maximum) element in constant time, while all other operations, including insertion, are O(log ''n'') or better. More generally, a [[self-balancing binary search tree]] can easily be augmented to make it possible to both insert an element and find the ''k''th largest element in O(log ''n'') time; this is called an ''[[order statistic tree]].'' We simply store in each node a count of how many descendants it has, and use this to determine which path to follow. The information can be updated efficiently since adding a node only affects the counts of its O(log ''n'') ancestors, and tree rotations only affect the counts of the nodes involved in the rotation.
 
== History==
Another simple strategy is based on some of the same concepts as the [[hash table]]. When we know the range of values beforehand, we can divide that range into ''h'' subintervals and assign these to ''h'' buckets. When we insert an element, we add it to the bucket corresponding to the interval it falls in. To find the minimum or maximum element, we scan from the beginning or end for the first nonempty bucket and find the minimum or maximum element in that bucket. In general, to find the ''k''th element, we maintain a count of the number of elements in each bucket, then scan the buckets from left to right adding up counts until we find the bucket containing the desired element, then use the expected linear-time algorithm to find the correct element in that bucket.
[[Quickselect]] was presented without analysis by [[Tony Hoare]] {{nowrap|in 1965,{{r|hoare}}}} and first analyzed in a 1971 technical report by {{nowrap|[[Donald Knuth]].{{r|floriv}}}} The first known linear time deterministic selection algorithm is the [[median of medians]] method, published in 1973 by [[Manuel Blum]], [[Robert W. Floyd]], [[Vaughan Pratt]], [[Ron Rivest]], and [[Robert Tarjan]].{{r|bfprt}} They trace the formulation of the selection problem to work of Charles L. Dodgson (better known as [[Lewis Carroll]]) who in 1883 pointed out that the usual design of single-elimination sports tournaments does not guarantee that the second-best player wins second place,{{r|bfprt|carroll}} and to work of [[Hugo Steinhaus]] circa 1930, who followed up this same line of thought by asking for a tournament design that can make this guarantee, with a minimum number of games played (that is, {{nowrap|comparisons).{{r|bfprt}}}}
 
== See also ==
If we choose ''h'' of size roughly sqrt(''n''), and the input is close to uniformly distributed, this scheme can perform selections in expected O(sqrt(''n'')) time. Unfortunately, this strategy is also sensitive to clustering of elements in a narrow interval, which may result in buckets with large numbers of elements (clustering can be eliminated through a good hash function, but finding the element with the ''k''th largest hash value isn't very useful). Additionally, like hash tables this structure requires table resizings to maintain efficiency as elements are added and ''n'' becomes much larger than ''h''<sup>2</sup>. A useful case of this is finding an order statistic or extremum in a finite range of data. Using above table with bucket interval 1 and maintaining counts in each bucket is much superior to other methods. Such hash tables are like [[frequency tables]] used to classify the data in [[descriptive statistics]].
* {{slink|Geometric median|Computation}}, algorithms for higher-dimensional generalizations of medians
* [[Median filter]], application of median-finding algorithms in image processing
 
== Lower boundsReferences ==
{{reflist|refs=
In ''[[The Art of Computer Programming]]'', [[Donald E. Knuth]] discussed a number of lower bounds for the number of comparisons required to locate the ''t'' smallest entries of an unorganized list of ''n'' items (using only comparisons). There is a trivial lower bound of ''n'' &minus; 1 for the minimum or maximum entry. To see this, consider a tournament where each game represents one comparison. Since every player except the winner of the tournament must lose a game before we know the winner, we have a lower bound of ''n'' &minus; 1 comparisons.
 
<ref name=akss>{{cite journal
The story becomes more complex for other indexes. We define <math>W_{t}(n)</math> as the minimum number of comparisons required to find the ''t'' smallest values. Knuth references a paper published by S. S. Kislitsyn, which shows an upper bound on this value:
| last1 = Ajtai | first1 = Miklós | author1-link = Miklós Ajtai
| last2 = Komlós | first2 = János | author2-link = János Komlós (mathematician)
| last3 = Steiger | first3 = W. L.
| last4 = Szemerédi | first4 = Endre | author4-link = Endre Szemerédi
| doi = 10.1016/0022-0000(89)90035-4
| issue = 1
| journal = [[Journal of Computer and System Sciences]]
| mr = 990052
| pages = 125–133
| title = Optimal parallel selection has complexity <math>O(\log\log n)</math>
| volume = 38
| year = 1989}}</ref>
 
<ref name=azapip>{{cite journal
:<math>W_{t}(n) \leq n - t + \sum_{n+1-t < j \leq n} \lceil{\log_2\, j}\rceil \quad \text{for}\, n \geq t</math>
| last1 = Azar | first1 = Yossi
| last2 = Pippenger | first2 = Nicholas | author2-link = Nick Pippenger
| doi = 10.1016/0166-218X(90)90128-Y
| issue = 1–2
| journal = [[Discrete Applied Mathematics]]
| mr = 1055590
| pages = 49–58
| title = Parallel selection
| volume = 27
| year = 1990}}</ref>
 
<ref name=benjoh>{{cite conference
This bound is achievable for ''t''=2 but better, more complex bounds are known for larger ''t''.
| last1 = Bent | first1 = Samuel W.
| last2 = John | first2 = John W.
| editor-last = Sedgewick | editor-first = Robert
| contribution = Finding the median requires <math>2n</math> comparisons
| doi = 10.1145/22145.22169
| pages = 213–216
| publisher = Association for Computing Machinery
| title = Proceedings of the 17th Annual ACM Symposium on Theory of Computing, May 6–8, 1985, Providence, Rhode Island, USA
| year = 1985| doi-access = free
| isbn = 0-89791-151-2
}}</ref>
 
<ref name=bfprt>{{cite journal
== Space complexity ==
| last1 = Blum | first1 = Manuel | author1-link = Manuel Blum
The required space complexity of selection is easily seen to be ''k'' + O(1) (or ''n''&nbsp;&minus;&nbsp;''k'' if ''k''&nbsp;>&nbsp;''n''/2), and in-place algorithms can select with only O(1) additional storage. ''k'' storage is necessary as the following data illustrates: start with 1, 2, ..., ''k,'' then continue with ''k''&nbsp;+&nbsp;1, ''k''&nbsp;+&nbsp;1, ..., ''k''&nbsp;+&nbsp;1, and finally finish with ''j'' copies of 0, where ''j'' is from 0 to ''k''&nbsp;&minus;&nbsp;1. In this case the ''k''th smallest element is one of 1, 2, ..., ''k,'' depending on the number of 0s, but this can only be determined at the end. One must store the initial ''k'' elements until near the end, since one cannot reduce the number of possibilities below the lowest ''k'' values until there are fewer than ''k'' elements left. Note that selecting the minimum (or maximum) by tracking the running minimum is a special case of this, with ''k''&nbsp;=&nbsp;1.
| last2 = Floyd | first2 = Robert W. | author2-link = Robert W. Floyd
| last3 = Pratt | first3 = Vaughan | author3-link = Vaughan Pratt
| last4 = Rivest | first4 = Ronald L. | author4-link = Ron Rivest
| last5 = Tarjan | first5 = Robert E. | author5-link = Robert Tarjan
| doi = 10.1016/S0022-0000(73)80033-9 | doi-access = free
| journal = [[Journal of Computer and System Sciences]]
| mr = 329916
| pages = 448–461
| title = Time bounds for selection
| url = http://people.csail.mit.edu/rivest/pubs/BFPRT73.pdf
| volume = 7
| year = 1973| issue = 4 }}</ref>
 
<ref name=bks>{{cite journal
This space complexity is achieved by doing a progressive partial sort – tracking a sorted list of the lowest ''k'' elements so far, such as by the partial insertion sort above. Note however that selection by partial sorting, while space-efficient, has superlinear time complexity, and that time-efficient partition-based selection algorithms require O(''n'') space.
| last1 = Babenko | first1 = Maxim
| last2 = Kolesnichenko | first2 = Ignat
| last3 = Smirnov | first3 = Ivan
| doi = 10.1007/s00224-018-9866-1
| issue = 4
| journal = Theory of Computing Systems
| mr = 3942251
| pages = 637–646
| title = Cascade heap: towards time-optimal extractions
| volume = 63
| year = 2019| s2cid = 253740380
}}</ref>
 
<ref name=brodal>{{cite conference
This space complexity bound helps explain the close connection between selecting the ''k''th element and selecting the (unordered) lowest ''k'' elements, as it shows that selecting the ''k''th element effectively requires selecting the lowest ''k'' elements as an intermediate step.
| last = Brodal | first = Gerth Stølting | author-link = Gerth Stølting Brodal
| editor1-last = Brodnik | editor1-first = Andrej
| editor2-last = López-Ortiz | editor2-first = Alejandro
| editor3-last = Raman | editor3-first = Venkatesh
| editor4-last = Viola | editor4-first = Alfredo
| contribution = A survey on priority queues
| doi = 10.1007/978-3-642-40273-9_11
| pages = 150–163
| publisher = Springer
| series = Lecture Notes in Computer Science
| title = Space-Efficient Data Structures, Streams, and Algorithms – Papers in Honor of J. Ian Munro on the Occasion of His 66th Birthday
| volume = 8066
| year = 2013| isbn = 978-3-642-40272-2 }}</ref>
 
<ref name=brown>{{cite journal
Space complexity is particularly an issue when ''k'' is a fixed fraction of ''n,'' particularly for computing the median, where ''k''&nbsp;=&nbsp;''n''/2, and in on-line algorithms. The space complexity can be reduced at the cost of only obtaining an approximate answer, or correct answer with certain probability; these are discussed below.
| last = Brown | first = Theodore
| date = September 1976
| doi = 10.1145/355694.355704
| issue = 3
| journal = ACM Transactions on Mathematical Software
| pages = 301–304
| title = Remark on Algorithm 489
| volume = 2| s2cid = 13985011
}}</ref>
 
<ref name=carroll>{{cite book|title=Lawn Tennis Tournaments: The True Method of Assigning Prizes with a Proof of the Fallacy of the Present Method|first=Charles L.|last=Dodgson|author-link=Lewis Carroll|year=1883|___location=London|publisher=Macmillan and Co.}} See also {{cite book|title=The Mathematical World of Charles L. Dodgson (Lewis Carroll)|editor1-first=Robin|editor1-last=Wilson|editor2-first=Amirouche|editor2-last=Moktefi|publisher=Oxford University Press|year=2019|isbn=9780192549013|contribution=Lawn tennis tournaments|page=129|contribution-url=https://books.google.com/books?id=OBGIDwAAQBAJ&pg=PA129}}</ref>
==Online selection algorithm==
[[online algorithm|Online]] selection may refer narrowly to computing the ''k''th smallest element of a stream, in which case partial sorting algorithms (with ''k'' + O(1)) space for the ''k'' smallest elements so far) can be used, but partition-based algorithms cannot be.
 
<ref name=chan>{{cite journal
Alternatively, selection itself may be required to be [[online algorithm|online]], that is, an element can only be selected from a sequential input at the instance of observation and each selection, respectively refusal, is irrevocable. The problem is to select, under these constraints, a specific element of the input sequence (as for example the largest or the smallest value) with largest probability. This problem can be tackled by the [[Odds algorithm]], which yields the optimal under an independence condition; it is also optimal itself as an algorithm with the number of computations being linear in the length of input.
| last = Chan | first = Timothy M. | author-link = Timothy M. Chan
| doi = 10.1145/1721837.1721842
| issue = 2
| journal = [[ACM Transactions on Algorithms]]
| mr = 2675693
| page = A26:1–A26:16
| title = Comparison-based time-space lower bounds for selection
| volume = 6
| year = 2010| s2cid = 11742607 }}</ref>
 
<ref name=chr>{{cite conference
The simplest example is the [[secretary problem]] of choosing the maximum with high probability, in which case optimal strategy (on random data) is to track the running maximum of the first ''n''/''e'' elements and reject them, and then select the first element that is higher than this maximum.
| last1 = Chaudhuri | first1 = Shiva
| last2 = Hagerup | first2 = Torben
| last3 = Raman | first3 = Rajeev
| editor1-last = Borzyszkowski | editor1-first = Andrzej M.
| editor2-last = Sokolowski | editor2-first = Stefan
| contribution = Approximate and exact deterministic parallel selection
| doi = 10.1007/3-540-57182-5_27
| pages = 352–361
| publisher = Springer
| series = Lecture Notes in Computer Science
| title = Mathematical Foundations of Computer Science 1993, 18th International Symposium, MFCS'93, Gdansk, Poland, August 30 – September 3, 1993, Proceedings
| volume = 711
| year = 1993| hdl = 11858/00-001M-0000-0014-B748-C
| isbn = 978-3-540-57182-7
| hdl-access = free
}}</ref>
 
<ref name=clrs>{{Introduction to Algorithms|edition=3|chapter=Chapter 9: Medians and order statistics|pages=213–227}}; "Section 14.1: Dynamic order statistics", pp. 339–345</ref>
== Related problems ==
One may generalize the selection problem to apply to ranges within a list, yielding the problem of [[Range Queries|range queries]]. The question of [[Range Queries#Median|range median queries]] (computing the medians of multiple ranges) has been analyzed.
 
<ref name=cormut>{{cite journal
== Language support ==
| last1 = Cormode | first1 = Graham
Very few languages have built-in support for general selection, although many provide facilities for finding the smallest or largest element of a list. A notable exception is [[C++]], which provides a templated <code>nth_element</code> method with a guarantee of expected linear time, and also partitions the data, requiring that the ''n''th element be sorted into its correct place, elements before the ''n''th element are less than it, and elements after the ''n''th element are greater than it. It is implied but not required that it is based on Hoare's algorithm (or some variant) by its requirement of expected linear time and partitioning of data.<ref>Section 25.3.2 of ISO/IEC 14882:2003(E) and 14882:1998(E)</ref><ref>[http://www.sgi.com/tech/stl/nth_element.html nth_element], SGI STL</ref>
| last2 = Muthukrishnan | first2 = S. | author2-link = S. Muthukrishnan (computer scientist)
| doi = 10.1016/j.jalgor.2003.12.001
| issue = 1
| journal = Journal of Algorithms
| mr = 2132028
| pages = 58–75
| title = An improved data stream summary: the count-min sketch and its applications
| volume = 55
| year = 2005}}</ref>
 
<ref name=cunmun>{{cite journal
For [[Perl]], the module [https://metacpan.org/module/Sort::Key::Top Sort::Key::Top], available from [[CPAN]], provides a set of functions to select the top n elements from a list using several orderings and custom key extraction procedures. Furthermore, the [https://metacpan.org/module/Statistics::CaseResampling Statistics::CaseResampling] module provides a function to calculate quantiles using quickselect.
| last1 = Cunto | first1 = Walter
| last2 = Munro | first2 = J. Ian | author2-link = Ian Munro (computer scientist)
| doi = 10.1145/62044.62047
| issue = 2
| journal = [[Journal of the ACM]]
| mr = 1072421
| pages = 270–279
| title = Average case selection
| volume = 36
| year = 1989| s2cid = 10947879
| doi-access = free
}}</ref>
 
<ref name=devroye>{{cite journal
[[Python (programming language)|Python]]'s standard library (since 2.4) includes <code>[https://docs.python.org/library/heapq.html heapq].nsmallest()</code> and <code>nlargest()</code>, returning sorted lists, in O(''n'' log ''k'') time.<ref>https://stackoverflow.com/a/23038826</ref>
| last = Devroye | first = Luc
| doi = 10.1016/0022-0000(84)90009-6
| issue = 1
| journal = Journal of Computer and System Sciences
| mr = 761047
| pages = 1–7
| title = Exponential bounds for the running time of a selection algorithm
| url = http://luc.devroye.org/devroye-selection1984.pdf
| volume = 29
| year = 1984}} {{cite journal
| last = Devroye | first = Luc
| doi = 10.1007/s00453-001-0046-2
| issue = 3
| journal = Algorithmica
| mr = 1855252
| pages = 291–303
| title = On the probabilistic worst-case time of 'find'
| url = https://luc.devroye.org/wcfind.pdf
| volume = 31
| year = 2001| s2cid = 674040
}}</ref>
 
<ref name=dieram>{{cite journal
Because [[sorting algorithm#Language support|language support for sorting]] is more ubiquitous, the simplistic approach of sorting followed by indexing is preferred in many environments despite its disadvantage in speed. Indeed, for [[Lazy evaluation|lazy languages]], this simplistic approach can even achieve the best complexity possible for the ''k'' smallest/greatest sorted (with maximum/minimum as a special case) if the sort is lazy enough{{Citation needed|date=April 2014}}.
| last1 = Dietz | first1 = Paul F.
| last2 = Raman | first2 = Rajeev
| doi = 10.1006/jagm.1998.0971
| issue = 1
| journal = [[Journal of Algorithms]]
| mr = 1661179
| pages = 33–51
| title = Small-rank selection in parallel, with applications to heap construction
| volume = 30
| year = 1999}}</ref>
 
<ref name=dz99>{{cite journal
== See also ==
| last1 = Dor | first1 = Dorit | author1-link = Dorit Dor
* [[Ordinal optimization]]
| last2 = Zwick | first2 = Uri | author2-link = Uri Zwick
| doi = 10.1137/S0097539795288611
| issue = 5
| journal = [[SIAM Journal on Computing]]
| mr = 1694164
| pages = 1722–1758
| title = Selecting the median
| volume = 28
| year = 1999| s2cid = 2633282
}}</ref>
 
<ref name=dz01>{{cite journal
== References ==
| last1 = Dor | first1 = Dorit | author1-link = Dorit Dor
{{reflist}}
| last2 = Zwick | first2 = Uri | author2-link = Uri Zwick
{{refbegin}}
| doi = 10.1137/S0895480199353895
* {{Cite journal | last1 = Blum | first1 = M. | authorlink1 = Manuel Blum| last2 = Floyd | first2 = R. W. | authorlink2 = Robert Floyd| last3 = Pratt | first3 = V. R. | authorlink3 = Vaughan Pratt| last4 = Rivest | first4 = R. L. | authorlink4 = Ron Rivest| last5 = Tarjan | first5 = R. E. | authorlink5 = Robert Tarjan | title = Time bounds for selection | doi = 10.1016/S0022-0000(73)80033-9 | journal = Journal of Computer and System Sciences | volume = 7 | issue = 4 | pages = 448–461 | date =August 1973 | url = http://people.csail.mit.edu/rivest/pubs/BFPRT73.pdf| ref = harv }}
| issue = 3
* {{Cite journal | last1 = Floyd | first1 = R. W. | authorlink1 = Robert W. Floyd | last2 = Rivest | first2 = R. L. | authorlink2 = Ron Rivest | doi = 10.1145/360680.360691 | title = Expected time bounds for selection | journal = Communications of the ACM | volume = 18 | issue = 3 | pages = 165–172 | date=March 1975 }}
| journal = [[SIAM Journal on Discrete Mathematics]]
* {{Cite journal | last1 = Kiwiel | first1 = K. C. | doi = 10.1016/j.tcs.2005.06.032 | title = On Floyd and Rivest's SELECT algorithm | journal = Theoretical Computer Science | volume = 347 | pages = 214–238 | year = 2005 | pmid = | pmc = }}
| mr = 1857348
* [[Donald Knuth]]. ''[[The Art of Computer Programming]]'', Volume 3: ''Sorting and Searching'', Third Edition. Addison-Wesley, 1997. {{ISBN|0-201-89685-0}}. Section 5.3.3: Minimum-Comparison Selection, pp.&nbsp;207&ndash;219.
| pages = 312–325
* [[Thomas H. Cormen]], [[Charles E. Leiserson]], [[Ronald L. Rivest]], and [[Clifford Stein]]. ''[[Introduction to Algorithms]]'', Second Edition. MIT Press and McGraw-Hill, 2001. {{ISBN|0-262-03293-7}}. Chapter 9: Medians and Order Statistics, pp.&nbsp;183&ndash;196. Section 14.1: Dynamic order statistics, pp.&nbsp;302&ndash;308.
| title = Median selection requires <math>(2+\varepsilon)N</math> comparisons
* {{DADS|Select|select}}
| volume = 14
{{refend}}
| year = 2001}}</ref>
 
<ref name=erickson>{{cite book|title=Algorithms|url=https://jeffe.cs.illinois.edu/teaching/algorithms/|first=Jeff|last=Erickson|date=June 2019|chapter=1.8: Linear-time selection|pages=35–39}}</ref>
==External links==
 
* "[http://www.ics.uci.edu/~eppstein/161/960125.html Lecture notes for January 25, 1996: Selection and order statistics]", ''ICS 161: Design and Analysis of Algorithms,'' David Eppstein
<ref name=floriv>{{cite journal
| last1 = Floyd | first1 = Robert W. | author1-link = Robert W. Floyd
| last2 = Rivest | first2 = Ronald L. | author2-link = Ron Rivest
| date = March 1975
| doi = 10.1145/360680.360691
| issue = 3
| journal = [[Communications of the ACM]]
| pages = 165–172
| s2cid = 3064709
| title = Expected time bounds for selection
| volume = 18| doi-access = free
}} See also "Algorithm 489: the algorithm SELECT—for finding the {{nowrap|<math>i</math>th}} smallest of <math>n</math> elements", p. 173, {{doi|10.1145/360680.360694}}.</ref>
 
<ref name=frederickson>{{cite journal
| last = Frederickson | first = Greg N.
| doi = 10.1006/inco.1993.1030
| issue = 2
| journal = [[Information and Computation]]
| mr = 1221889
| pages = 197–214
| title = An optimal algorithm for selection in a min-heap
| volume = 104
| year = 1993| doi-access = free
}}</ref>
 
<ref name=frejoh>{{cite journal
| last1 = Frederickson | first1 = Greg N.
| last2 = Johnson | first2 = Donald B. | author2-link = Donald B. Johnson
| doi = 10.1137/0213002
| issue = 1
| journal = [[SIAM Journal on Computing]]
| mr = 731024
| pages = 14–30
| title = Generalized selection and ranking: sorted matrices
| volume = 13
| year = 1984}}</ref>
 
<ref name=gkp>{{cite journal
| last1 = Gasarch | first1 = William | author1-link = William Gasarch
| last2 = Kelly | first2 = Wayne
| last3 = Pugh | first3 = William
| date = July 1996
| doi = 10.1145/235767.235772
| issue = 2
| journal = [[ACM SIGACT News]]
| pages = 88–96
| title = Finding the {{nowrap|<math>i</math>th}} largest of <math>n</math> for small <math>i,n</math>
| volume = 27| s2cid = 3133332 }}</ref>
 
<ref name=gootam>{{cite book|title=Algorithm Design and Applications|first1=Michael T.|last1=Goodrich|author1-link= Michael T. Goodrich|first2=Roberto|last2=Tamassia|author2-link=Roberto Tamassia|publisher=Wiley|year=2015|chapter=9.2: Selection|pages=270–275|isbn=978-1-118-33591-8}}</ref>
 
<ref name=gurwitz>{{cite journal
| last = Gurwitz | first = Chaya
| doi = 10.1109/13.144650
| issue = 3
| journal = IEEE Transactions on Education
| pages = 230–232
| title = On teaching median-finding algorithms
| volume = 35
| year = 1992| bibcode = 1992ITEdu..35..230G
}}</ref>
 
<ref name=hadsob>{{cite report|first1=Abdollah|last1=Hadian|first2=Milton|last2=Sobel|author2-link=Milton Sobel|hdl=11299/199105|series=School of Statistics Technical Reports|volume=121|publisher=University of Minnesota|title=Selecting the {{nowrap|<math>t</math>-th}} largest using binary errorless comparisons|date=May 1969}}</ref>
 
<ref name=han>{{cite journal
| last = Han | first = Yijie
| doi = 10.1145/1290672.1290675
| issue = 4
| journal = [[ACM Transactions on Algorithms]]
| mr = 2364962
| page = A38:1–A38:11
| title = Optimal parallel selection
| volume = 3
| year = 2007| s2cid = 9645870
}}</ref>
 
<ref name=hoare>{{cite journal
| last = Hoare | first = C. A. R. | author-link = Tony Hoare
| date = July 1961
| doi = 10.1145/366622.366647
| issue = 7
| journal = [[Communications of the ACM]]
| pages = 321–322
| title = Algorithm 65: Find
| volume = 4}}</ref>
 
<ref name=karrag>{{cite journal
| last1 = Karloff | first1 = Howard J.
| last2 = Raghavan | first2 = Prabhakar | author2-link = Prabhakar Raghavan
| doi = 10.1145/174130.174132
| issue = 3
| journal = [[Journal of the ACM]]
| mr = 1370358
| pages = 454–476
| title = Randomized algorithms and pseudorandom numbers
| volume = 40
| year = 1993| s2cid = 17956460
| doi-access = free
}}</ref>
 
<ref name=kkzz>{{cite conference
| last1 = Kaplan | first1 = Haim
| last2 = Kozma | first2 = László
| last3 = Zamir | first3 = Or
| last4 = Zwick | first4 = Uri | author4-link = Uri Zwick
| editor1-last = Fineman | editor1-first = Jeremy T.
| editor2-last = Mitzenmacher | editor2-first = Michael | editor2-link = Michael Mitzenmacher
| arxiv = 1802.07041
| contribution = Selection from heaps, row-sorted matrices, and <math>X+Y</math> using soft heaps
| doi = 10.4230/OASIcs.SOSA.2019.5
| pages = 5:1–5:21
| publisher = Schloss Dagstuhl – Leibniz-Zentrum für Informatik
| series = OASIcs
| title = 2nd Symposium on Simplicity in Algorithms, SOSA 2019, January 8–9, 2019, San Diego, CA, USA
| volume = 69
| year = 2019| doi-access = free
}}</ref>
 
<ref name=kletar>{{cite book
| last1 = Kleinberg | first1 = Jon | author1-link = Jon Kleinberg
| last2 = Tardos | first2 = Éva | author2-link = Éva Tardos
| contribution = 13.5 Randomized divide and conquer: median-finding and quicksort
| isbn = 9780321295354
| pages = 727–734
| publisher = Addison-Wesley
| title = Algorithm Design
| year = 2006}}</ref>
 
<ref name=knuth>{{cite book
| last = Knuth | first = Donald E. | author-link = Donald Knuth
| contribution = Section 5.3.3: Minimum-comparison selection
| edition = 2nd
| isbn = 0-201-89685-0
| pages = 207–219
| publisher = Addison-Wesley
| title = The Art of Computer Programming, Volume 3: Sorting and Searching
| title-link = The Art of Computer Programming
| year = 1998}}</ref>
 
<ref name=kpaths>{{cite journal
| last = Eppstein | first = David | author-link = David Eppstein
| doi = 10.1137/S0097539795290477
| issue = 2
| journal = [[SIAM Journal on Computing]]
| mr = 1634364
| pages = 652–673
| title = Finding the <math>k</math> shortest paths
| volume = 28
| year = 1999}}</ref>
 
<ref name=musser>{{cite journal
| last = Musser | first = David R.
| date = August 1997
| doi = 10.1002/(sici)1097-024x(199708)27:8<983::aid-spe117>3.0.co;2-#
| issue = 8
| journal = Software: Practice and Experience
| pages = 983–993
| publisher = Wiley
| title = Introspective sorting and selection algorithms
| volume = 27}}</ref>
 
<ref name=pattho>{{cite conference
| last1 = Pătraşcu | first1 = Mihai | author1-link = Mihai Pătrașcu (computer scientist)
| last2 = Thorup | first2 = Mikkel
| arxiv = 1408.3045
| contribution = Dynamic integer sets with optimal rank, select, and predecessor search
| doi = 10.1109/FOCS.2014.26
| pages = 166–175
| publisher = IEEE Computer Society
| title = 55th IEEE Annual Symposium on Foundations of Computer Science, FOCS 2014, Philadelphia, PA, USA, October 18–21, 2014
| year = 2014| isbn = 978-1-4799-6517-5 }}</ref>
 
<ref name=prt>{{cite journal
| last1 = Postmus | first1 = J. T.
| last2 = Rinnooy Kan | first2 = A. H. G. | author2-link = Alexander Rinnooy Kan
| last3 = Timmer | first3 = G. T.
| doi = 10.1145/182.358440
| issue = 11
| journal = [[Communications of the ACM]]
| mr = 784120
| pages = 878–881
| title = An efficient dynamic selection method
| volume = 26
| year = 1983| s2cid = 3211474
| doi-access = free
}}</ref>
 
<ref name=reischuk>{{cite journal
| last = Reischuk | first = Rüdiger
| doi = 10.1137/0214030
| issue = 2
| journal = [[SIAM Journal on Computing]]
| mr = 784745
| pages = 396–409
| title = Probabilistic parallel algorithms for sorting and selection
| volume = 14
| year = 1985}}</ref>
 
<ref name=skiena>{{cite book
| last = Skiena | first = Steven S. | author-link = Steven Skiena
| chapter = 17.3: Median and selection
| doi = 10.1007/978-3-030-54256-6
| edition = Third
| isbn = 978-3-030-54255-9
| mr = 4241430
| pages = 514–516
| publisher = Springer
| series = Texts in Computer Science
| title = The Algorithm Design Manual
| year = 2020| s2cid = 22382667 }}</ref>
 
<ref name=spp>{{cite journal
| last1 = Schönhage | first1 = A. | author1-link = Arnold Schönhage
| last2 = Paterson | first2 = M. | author2-link = Mike Paterson
| last3 = Pippenger | first3 = N. | author3-link = Nick Pippenger
| doi = 10.1016/S0022-0000(76)80029-3
| issue = 2
| journal = [[Journal of Computer and System Sciences]]
| mr = 428794
| pages = 184–199
| title = Finding the median
| volume = 13
| year = 1976| s2cid = 29867292 }}</ref>
 
<ref name=valiant>{{cite journal
| last = Valiant | first = Leslie G. | author-link = Leslie Valiant
| doi = 10.1137/0204030
| issue = 3
| journal = [[SIAM Journal on Computing]]
| mr = 378467
| pages = 348–355
| title = Parallelism in comparison problems
| volume = 4
| year = 1975}}</ref>
 
<ref name=matlab>{{cite web|url=https://www.mathworks.com/help/matlab/ref/mink.html|title=mink: Find k smallest elements of array|work=Matlab R2023a documentation|publisher=Mathworks|access-date=2023-03-30}}</ref>
 
<ref name=python>{{cite web|url=https://github.com/python/cpython/blob/main/Lib/heapq.py|title=heapq package source code|work=Python library|access-date=2023-08-06}}; see also the linked [https://code.activestate.com/recipes/577573-compare-algorithms-for-heapqsmallest/ comparison of algorithm performance on best-case data].</ref>
 
}}
 
{{DEFAULTSORT:Selection Algorithm}}
[[Category:Selection algorithms| ]]
 
[[ru:BFPRT-Алгоритм]]