The problem to find the kth largest element in an unsorted array. Note that it is the kth largest element in the sorted order, not the kth distinct element.

For example,
Given [3,2,1,5,6,4] and k = 2, return 5.

# Simplest Solution - Sort and Index

The most straightforward solution to this problem is sort and return the $k$ element in the sorted list.

The performance is as follows. The complexity of the time is $O(nlogn)$ and space is $O(1)$. The runtime of the algorithm is not too bad in the testcases.

# Partition Solution

As we know, the general complexity of sort algorithm $nlogn$. But we actually dont need the sort the whole list. In this case, we can find any $k$ instead of particular k. Therefore, we can better instead of sorting whole list. One popular sorting algorithm is quick sort. We can look into details of the algorithm.

In quick sort, it keeps partitioning the list based on a pivot. The numbers that are bigger than the pivot will be put in the left $i+1$ and other numbers will be put in the right.
Combining the partition step and binary search, we can keep the process untill the number of left we put in the left is $k$. Here is the implementation.

The complexity if $O(n)$ in time and $O(1)$ in space.

# Ganrantee the Average Performance

The common way to avoid the effect of worst cases in sorting can be applied here too. We can randomize the input to avoid the worst case.

The performance is as follows. 