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)
- Karatsuba algorithm for fast multiplication using Divide and Conquer algorithm
- Quickselect Algorithm
- In-Place Algorithm
- LRU Approximation (Second Chance Algorithm)
- Painting Fence Algorithm
- Distinct elements in subarray using Mo's Algorithm
- Generic Implementation of QuickSort Algorithm in C
- Reversal algorithm for right rotation of an array
- Randomized Binary Search Algorithm
- Quickhull Algorithm for Convex Hull
- Divide and Conquer Algorithm | Introduction
- Reversal algorithm for array rotation
- Convex Hull using Divide and Conquer Algorithm
- The Skyline Problem using Divide and Conquer algorithm
- Tiling Problem using Divide and Conquer algorithm
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to firstname.lastname@example.org. 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