Quick Sort Algorithm

Maryann Gitonga
2 min readSep 4, 2023

--

How it works

Imagine you have a big box of unsorted books, and you want to arrange them in alphabetical order. With quick sort, you don’t start with smaller piles like in merge-sort. Instead, you pick one book from the box and call it the “pivot.”

Now, you quickly glance through all the other books and decide whether each should go to the left or right of the pivot based on their titles. As you do this, you’re essentially dividing the books into two groups: those before the pivot (let’s call this “A”) and those after the pivot (“B”).

Next, you repeat this process for groups A and B. You select a new pivot for each group and again divide the books into smaller groups based on their titles. You keep doing this until each group is so small that it’s effectively sorted.

Finally, you merge these sorted groups back together, and because you’ve made good choices with the pivots all along, the books come together in alphabetical order. This is Quick Sort.

Illustration of Quick Sort

Benefits

  1. Efficient for Large Datasets: It is much faster than methods like inserting the books one by one or repeatedly comparing adjacent books.
  2. Saves Memory: It sorts the data in-place, which means it doesn’t require additional memory for temporary storage.

Note: In quicksort, choosing a bad pivot can make the algorithm very slow, especially when dealing with large datasets. This can happen when the pivot ends up being the smallest or largest element in the array, causing a major imbalance in the partitioning process. In such cases, one sub-array gets much smaller, while the other remains almost the same size. To avoid this, algorithms for smarter pivot selection are used to keep quicksort efficient.

Real-life application

Music streaming platforms could use quick sort algorithms for sorting playlists, top charts and recommended songs.

In music streaming platforms, the quick sort algorithm can be useful for arranging playlists, top charts, and recommended songs. It can efficiently organize these songs, placing the most relevant and enjoyable tracks at the top of your playlists and charts.

Simple Code Illustration

Where next?

--

--

Maryann Gitonga

A Software Engineer who loves trying out different tooling & engineering concepts in Back-end Engineering & DevOps. An explorer in the ML world too!