spiralgo / algorithms

We voluntarily solve algorithm problems on this repo.
24 stars 7 forks source link

Quickselect Algorithm #362

Closed ErdemT09 closed 3 years ago

ErdemT09 commented 3 years ago

Qucikselect is an algorithm used for finding the kth smallest element in an unsorted list. Its procedure of doing this contains similarites to the quicksort algorithm, they are both developed by Tony Hoare. In an array, it's rather trivial to find the maximum or the minimum. But things get hard if we are trying to find the median or the 12th smallest element out of 100. We can of course sort, but that would take linearithmic time. Quickselect performs in linear time on avarage, it partially sorts the array as well. To find the kth smallest element, we choose some random pivot. We then transfer every element smaller than this pivot the the start of the array. If the transfer index, new pivot, is greater than k, that means that the kth element is among these. If the new pivot is larger, that means that the kth element is among the elements that were not transferred. So, we partition the array each time and eventually find the kth element.

It could also be implemented as an iterative algorithm, where we can also move right elements to the other side of the pivot.