1

There's a famous question posted on this site which asks about finding the $k$th largest element. Many answers are written there which optimized it and found algorithms with expectation of $O(n)$.

The thing I don't understand is.... Those algorithms wouldn't work if $k$ is dependent on $N$. Therefore $k$ must be a constant.

But if it's a constant why isn't it easiest to simply loop like bubble sort for $k$ times? So you pushed the $k$ largest elements to the end of the array. No? Complexity would be $O(nk)$ but $k$ is a const so it would be $O(n)$.

Why do we need crazy algorithms like median of medians and using quicksort if this alone works?

xskxzr
  • 7,613
  • 5
  • 24
  • 47
bilanush
  • 263
  • 1
  • 8

1 Answers1

1

The $k$th largest element can be found in time $O(n)$ for all $k$ using a deterministic algorithm. See Wikipedia or many textbooks, such as Cormen et al., Introduction to Algorithms.

Given the $k$th largest element, you can find the $k$ largest elements in $O(n)$ using a simple scan. If all elements are distinct, you just output all elements which are at least as large as the $k$th largest. Without this assumption, you output all elements which are strictly larger than that element, and then enough copies of the $k$th largest one.

Yuval Filmus
  • 280,205
  • 27
  • 317
  • 514