The Floyd-Rivest algorithm is a selection algorithm used to find the kth smallest element in an array of distinct elements. It is similar to the QuickSelect algorithm but has better running time in practice.
Like QuickSelect the algorithm works on the idea of partitioning. After partitioning an array, the partition element ends up in the corrected sorted position. If the array has all distinct elements, retrieving the (k+1)th smallest element is same as retrieving the (k+1)th element after sorting. Because a full sort is expensive(takes O(N log N) to compute), the Floyd-Rivest algorithm leverages partitioning to accomplish the same in O(N) time.
- If the size of the array S being considered is small enough, then the QuickSelect algorithm is applied directly to get the K-th smallest element. This size is an arbitrary constant of the algorithm, which the authors chose as 600.
- Otherwise, 2 pivots are chosen- newLeftIndex and newRightIndex using random sampling such that they have the highest probability of containing the K-th largest element. Then, the function is called recursively with left and right boundaries of the array now set to newLeftIndex and newRightIndex.
- Like QuickSelect, after partitioning the subarray, the left and right boundaries need to be set such that they contain the K-largest element.
After partitioning the array around K, the Kth element is in its correct sorted position. So, the left and right boundaries are set in such a way that the subarray being considered contains array[k]
Below is the implementation of the above approach.
The 2-th smallest element is 1
Time complexity: O(N)
GeeksforGeeks has prepared a complete interview preparation course with premium videos, theory, practice problems, TA support and many more features. Please refer Placement 100 for details
- Karatsuba algorithm for fast multiplication using Divide and Conquer algorithm
- In-Place Algorithm
- Quickselect Algorithm
- LRU Approximation (Second Chance Algorithm)
- Painting Fence Algorithm
- Generic Implementation of QuickSort Algorithm in C
- Distinct elements in subarray using Mo's Algorithm
- Randomized Binary Search Algorithm
- Quickhull Algorithm for Convex Hull
- Reversal algorithm for right rotation of an array
- Divide and Conquer Algorithm | Introduction
- Reversal algorithm for array rotation
- Convex Hull using Divide and Conquer Algorithm
- Advanced Quick Sort (Hybrid Algorithm)
- Block swap algorithm for array rotation
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to email@example.com. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.
Improved By : AnkitRai01