Thanks to visit codestin.com
Credit goes to github.com

Skip to content

Commit a0d1a9b

Browse files
author
Oleksandr Kulkov
authored
A bit more info on selection algorithms
1 parent 5d3b001 commit a0d1a9b

File tree

1 file changed

+7
-4
lines changed

1 file changed

+7
-4
lines changed

src/sequences/k-th.md

Lines changed: 7 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -3,11 +3,11 @@ title: K-th order statistic in O(N)
33
---
44
# $K$th order statistic in $O(N)$
55

6-
Given an array __A__ of size __N__ and a number __K__. The challenge is to find __K__-th largest number in the array, i.e., __K__-th order statistic.
6+
Given an array $A$ of size $N$ and a number $K$. The problem is to find $K$-th largest number in the array, i.e., $K$-th order statistic.
77

8-
The basic idea - to use the idea of quick sort algorithm. Actually, the algorithm is simple, it is more difficult to prove that it runs in an average of O(N), in contrast to the quick sort.
8+
The basic idea - to use the idea of quick sort algorithm. Actually, the algorithm is simple, it is more difficult to prove that it runs in an average of $O(N)$, in contrast to the quick sort.
99

10-
## Implementation (not recursive):
10+
## Implementation (not recursive)
1111

1212
```cpp
1313
template <class T>
@@ -63,7 +63,10 @@ T order_statistics (std::vector<T> a, unsigned n, unsigned k)
6363
}
6464
```
6565
66-
To note, in the standard C ++ library, this algorithm has already been implemented - it is called nth_element.
66+
## Notes
67+
* The randomized algorithm above is named [quickselect](https://en.wikipedia.org/wiki/Quickselect). You should do random shuffle on $A$ before calling it or use a random element as a barrier for it to run properly. There are also deterministic algorithms that solve the specified problem in linear time, such as [median of medians](https://en.wikipedia.org/wiki/Median_of_medians).
68+
* A deterministic linear solution is implemented in C++ standard library as [std::nth_element](https://en.cppreference.com/w/cpp/algorithm/nth_element).
69+
* Finding $K$ smallest elements can be reduced to finding $K$-th element with a linear overhead, as they're exactly the elements that are smaller than $K$-th.
6770
6871
## Practice Problems
6972

0 commit comments

Comments
 (0)