In quicksort, there is a subprocedure called partition that can, in linear time, group a list (ranging from indices left to right) into two parts: those less than a certain element, and those greater than or equal to the element. Here is pseudocode that performs a partition about the element list[pivotIndex]:
function partition(list, left, right, pivotIndex)
is pivotValue := list[pivotIndex] swap list[pivotIndex] and list[right]
// Move pivot to end storeIndex := left
for i
from left
to right − 1
do if list[i] O(n\log n) time. However, when doing selection, we already know which partition our desired element lies in, since the pivot is in its final sorted position, with all those preceding it in an unsorted order and all those following it in an unsorted order. Therefore, a single recursive call locates the desired element in the correct partition, and we build upon this for quickselect:
// Returns the k-th smallest element of list within left..right inclusive ''// (i.e. left O(\log n) of its O(n) partitions. This simple procedure has expected linear performance, and, like quicksort, has quite good performance in practice. It is also an
in-place algorithm, requiring only constant memory overhead if
tail call optimization is available, or if eliminating the
tail recursion with a loop:
function select(list, left, right, k)
is loop if left = right
then return list[left] pivotIndex := ...
// select pivotIndex between left and right pivotIndex := partition(list, left, right, pivotIndex)
if k = pivotIndex
then return list[k]
else if k select function works only with the
Lomuto partition scheme. This is because select assumes that the return value from partition is the position of the pivot. This is true for the
Lomuto partition scheme, but not for the
Hoare's partition scheme. In Hoare's scheme, the return value is the last index of the "left" partition, and the pivot is not guaranteed to be "in between" the partitions. The recursion, as presented, also only works with Lomuto's scheme, as it assumes that the right partition starts with pivotIndex +1, while when using Hoare's scheme, the right partition starts at pivotIndex. ==Time complexity==