Nerd For Tech
Published in

Nerd For Tech

Implementing Quick Select in Ruby

In this blog, we’ll walk through how to write the Quick Select algorithm in Ruby. This technique is used to find the kth smallest element in an unsorted array, with an average runtime complexity of O(n). Quick Select uses a similar approach to the popular Quick Sort algorithm. It is a divide and conquer approach where the array to search is cut into smaller and smaller pieces until the desired result is found.

At first glance, finding the kth smallest element of an array is simple. Just sort the array and pick the element at the index [k - 1]. However, if we do it like this, we will only be as fast as our sorting method, which in most cases is slower than O(n). Using Quick Select thus will ensure we are the most efficient we can be when solving the problem.

The first thing to do is write a partition method. This method has only one purpose: to return the index of a sorted element in an array. We pass in an array along with the section of it to look at via a low and high index.

partition method

This method goes through the selected section of the array and swaps the elements based on their relationship to our chosen pivot element, in this case we chose the element corresponding to the high index. A fantastic explanation of this process can be found here.

Now that we have our partition algorithm to find sorted indexes of an unsorted array, we need to write a method to find our element in question!

The arguments passed in to this method are the array in question, the left index, the right index, and of course k which tells us to return the kth smallest element of the array. When we first call this method, the left and right indexes will be 0 and the length of the array minus 1, respectively. As the method recursively calls itself, the distance between left and right will shrink by half each time.

Here are the steps:

quick_select technique

And there we are, by the end we will have found the element we are looking for.

I like this algorithm because it is sneaky in the fact that we don’t need to sort the array. All we need to do is keep finding the index of certain elements in their proper sorted position and we will eventually achieve our goal. This makes Quick Select an awesome choice to search for a particular element.

--

--

NFT is an Educational Media House. Our mission is to bring the invaluable knowledge and experiences of experts from all over the world to the novice. To know more about us, visit https://www.nerdfortech.org/.

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store