Five cross sections of citrus fruits arranged in ascending order of diameter on a textured grey background. From left to right, they appear to be a lime, a lemon, and orange, a larger orange citrus fruit, and a red grapefruit.
Photo by Andre Taissin on Unsplash

Quicksort the Ruby Way

I’m gearing up to apply for my next engineering job by reviewing some classic algorithms and implementing them in Ruby.

Quicksort is a recursive algorithm for sorting lists of values. I won’t recapitulate the details of how quicksort works here. This explanation from Khan Academy is good. I used the JavaScript implementation developed in that course as the basis for my own.

This post is for folks who write Ruby and want to see what an idiomatic Ruby implementation of quicksort might look like. In particular, I’ve eschewed the overly terse single-letter-variable salad you so often find in example implementations of basic algorithms.

Here’s the code, followed by some basic RSpec unit tests.

Quicksort Implementation

Quicksort Unit Tests



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