The Floyd-Rivest algorithm is a divide and conquer algorithm, sharing many similarities with quickselect. It uses sampling to help partition the list into three sets. It then recursively selects the kthsmallest element from the appropriate set. The general steps are:
From S, recursively select two elements, u and v, such that u < v. These two elements will be the pivots for the partition and are expected to contain the kth smallest element of the entire list between them.
Using u and v, partition S into three sets: A, B, and C. A will contain the elements with values less than u, B will contain the elements with values between u and v, and C will contain the elements with values greater thanv.
Partition the remaining elements in L by comparing them to u or v and placing them into the appropriate set. If k is smaller than half the number of the elements in L rounded up, then the remaining elements should be compared to v first and then only to u if they are smaller than v. Otherwise, the remaining elements should be compared to u first and only to v if they are greater than u.
Based on the value of k, apply the algorithm recursively to the appropriate set to select the kth smallest element in L.
Pseudocode version
The following pseudocode sorts the elements between left and right in ascending order, such that for some value k, where left ≤ k ≤ right, the kth element in the list will contain the th smallest value: // left is the left index for the interval // right is the right index for the interval // k is the desired index value, where array is the th smallest element when left = 0 function select is whileright > leftdo // Use select recursively to sample a smaller set of size s // the arbitrary constants 600 and 0.5 are used in the original // version to minimize execution time. if right − left > 600 then n := right − left + 1 i := k − left + 1 z := ln s := 0.5 × exp sd := 0.5 × sqrt × sign newLeft := max newRight := min select // partition the elements between left and right around t t := array i := left j := right swap array and array if array > t then swap array and array while i < j do swap array and array i := i + 1 j := j − 1 while array < t do i := i + 1 while array > t do j := j − 1 if array = t then swap array and array else j := j + 1 swap array and array // Adjust left and right towards the boundaries of the subset // containing the th smallest element. if j ≤ k then left := j + 1 if k ≤ j then right := j − 1