Quick Sort: A Beginner-Friendly Guide with TypeScript

Nikita Babanin
7 min readDec 5, 2023

--

Animation from the “Algorithms app

Hey fellow coders! 🚀

Today, we’re diving into the world of sorting algorithms, and the star of our show is Quick Sort. Think of it as the ninja of sorting techniques: stealthy, swift, and impressively efficient. But like any good ninja, it’s got its mystique and complexities.

Imagine you’re at a magic show, where the magician effortlessly sorts a deck of cards in a blink. That’s Quick Sort for you in the algorithm world. It’s not just about being fast; it’s about being smart and knowing how to tackle problems from the right angle.

As programmers, we often encounter various sorting challenges, from organizing simple number arrays to handling complex data structures. Quick Sort comes to the rescue, offering not just speed but also a clever approach to sorting. It’s a fundamental tool in our coding arsenal, but one that can seem daunting at first glance.

But fear not! I’m here to demystify Quick Sort for you. We’ll break it down together, step by step, and by the end of this, you’ll see why it’s a go-to algorithm for efficiency and performance. Let’s unravel the magic and mechanics of Quick Sort, making it as easy to understand as enjoying a good show

Quick Sort: The Art of Efficient Sorting

Imagine you’re at a game night with friends, and you have a deck of playing cards that’s all over the place. One way to organize them is to go through each card one by one, similar to how Bubble Sort works — it’s straightforward but not very efficient. Another method might be to sort smaller groups of cards and then combine them, much like Merge Sort, which is more efficient but still can be improved upon. But what if there’s a method that’s not just more efficient, but also faster and smarter? That’s where Quick Sort comes into play.

Quick Sort is like the clever trick in your sorting hat. It doesn’t just plow through the deck; it picks a card, let’s call it a ‘pivot’, and uses it as a benchmark to organize the rest. The beauty of Quick Sort lies in how it handles the cards (or data) around this pivot. Instead of tackling the entire deck head-on, Quick Sort divides the deck into smaller, more manageable sections based on the pivot, and then sorts each section. This method of breaking down the problem into smaller pieces is a classic example of the ‘divide and conquer’ strategy in computer science.

But here’s the real magic: once these smaller sections are sorted, Quick Sort combines them back together. And voila, your deck is sorted much faster than if you had used simpler methods. This speed and efficiency make Quick Sort a preferred choice, especially when dealing with large arrays or databases where every second of processing time is valuable.

In essence, Quick Sort doesn’t just sort; it strategically organizes data using a pivot to minimize the number of comparisons and swaps needed. This approach not only speeds up the sorting process but also makes it more efficient, particularly for large datasets where traditional sorting methods might stumble.

So, as you see, Quick Sort isn’t just a sorting algorithm; it’s a smart, strategic way of organizing data that’s both fast and efficient, making it a valuable skill for any programmer to master.

The Magic Trick: Picking a Pivot

In the fascinating world of Quick Sort, the first act is akin to a magician’s opening trick: selecting a ‘pivot’. This isn’t just any random pick; it’s a strategic choice that sets the stage for the entire sorting process. Think of it like choosing a pivotal card from a deck, and then announcing, “Cards higher than this, go to the right; those lower, to the left.” This pivotal card, or pivot, becomes the cornerstone for dividing the deck — or in our programming scenario, the array — into two distinct parts.

But why is this pivot so crucial? Well, it’s all about positioning. By placing the pivot in the right spot, you can ensure that all elements to its left are smaller and all to its right are larger. This process might seem simple, but it’s a powerful tool in efficiently organizing the data. It’s like having a reference point that helps you quickly decide where each element belongs, cutting down the time it takes to sort the entire array.

Choosing the right pivot is part art and part science. Some common strategies include picking the first element, the last element, the middle one, or even a random element. Each method has its pros and cons, but they all serve the same purpose: helping to reduce the problem size by half with each pass of the algorithm.

Once the pivot is selected, Quick Sort performs its magic by rearranging the other elements around it. Those lesser than the pivot move to one side, and those greater move to the other. This crucial step is where Quick Sort shines, using the pivot as a fulcrum to balance and sort the data. It’s like organizing a chaotic room by first finding a central point to work around, making the task less daunting and more systematic.

In essence, the act of picking a pivot in Quick Sort isn’t just a random step; it’s a strategic decision that significantly influences the efficiency of the sorting process. It’s the magic trick that sets the stage for the rest of the algorithm, ensuring that each move thereafter is quicker and more effective.

Divide and Conquer, Quick Sort Style

Here’s how it rolls:

  1. Choose a Pivot: Let’s say you pick a number from the array randomly.
  2. Partitioning: Arrange the array so that all numbers less than the pivot come before it, and all numbers greater come after it. Now, our pivot is in its final position.
  3. Repeat: Apply the same logic to the numbers on either side of the pivot.

The cool part? This ‘divide and conquer’ approach makes sorting super-fast, especially for large arrays.

Why Quick Sort Rocks

Quick Sort’s beauty lies in its speed. It typically runs faster than other sorting methods like Bubble or Merge Sort, thanks to its ability to handle large datasets effectively. Its average time complexity is O(n log n), similar to Merge Sort, but in practice, it’s often quicker.

Quick Sort in Action: A TypeScript Example

To truly grasp the elegance of Quick Sort, it’s helpful to see it in action. Here, we have a basic implementation in TypeScript, a superset of JavaScript that adds types to make our code more robust and understandable. Let’s break down how this code brings the Quick Sort algorithm to life:

function quickSort(arr: number[]): number[] {
if (arr.length <= 1) {
return arr;
}

const pivot = arr[arr.length - 1];
const leftArr = [];
const rightArr = [];

for (let i = 0; i < arr.length - 1; i++) {
if (arr[i] < pivot) {
leftArr.push(arr[i]);
} else {
rightArr.push(arr[i]);
}
}

return [...quickSort(leftArr), pivot, ...quickSort(rightArr)];
}

const unsortedArray = [5, 1, 4, 2, 7, 3, 6];
console.log(quickSort(unsortedArray));

Understanding the Code: Step by Step

  1. Base Case: Our function quickSort takes an array of numbers as input. The first thing we do is check if the array has one or no elements (arr.length <= 1). If so, there's nothing to sort, so we just return the array as is. This is our base case, preventing the function from running infinitely.
  2. Choosing a Pivot: We pick the last element in the array as the pivot (const pivot = arr[arr.length - 1]). This choice is arbitrary, and different methods can be used to choose the pivot. The key idea is to have a reference point to compare other elements against.
  3. Partitioning the Array: Next, we create two new arrays, leftArr and rightArr. We iterate through each element in our input array (excluding the pivot), comparing them with the pivot. If an element is less than the pivot, it goes into leftArr; if it's greater, into rightArr. This step effectively partitions the array around our pivot.
  4. Recursive Sorting: Here’s where the magic happens. We call quickSort recursively on both leftArr and rightArr. This recursive call continues to break down the arrays until they satisfy the base case (i.e., they have one or no elements).
  5. Merging and Returning: Finally, we combine (or merge) our sorted subarrays and the pivot back into a single array using the spread operator [...quickSort(leftArr), pivot, ...quickSort(rightArr)]. This line is the essence of Quick Sort, where we continuously merge smaller sorted arrays into larger ones until the entire array is sorted.

Trying It Out

We test our quickSort function with an unsorted array [5, 1, 4, 2, 7, 3, 6]. After running the code, the console logs a neatly sorted array, showcasing Quick Sort's efficiency.

Why This Matters

This TypeScript example not only shows Quick Sort in action but also demonstrates the power of recursion and partitioning in sorting algorithms. Understanding and implementing Quick Sort in a programming language like TypeScript provides a deeper appreciation of its efficiency and elegance, especially when dealing with complex, real-world data sets.

When to Use Quick Sort

Quick Sort is perfect when you need to sort large datasets quickly. It’s widely used in libraries and systems where performance matters. However, its performance can degrade if the pivot selection isn’t optimal or the array is already sorted (worst-case scenario).

Wrapping Up

That’s the gist of Quick Sort! It’s like being at a magician’s show, where the deck is sorted before you even know it. Understanding Quick Sort not only helps in sorting tasks but also improves your grasp of efficient algorithms.

Jumping into algorithms can be way cooler with the right tools.I used animation from the “Algorithms apphere to make things clearer. It’s a great app with loads of helpful examples. Give it a try!

Feel free to tinker with the TypeScript code. Try different arrays and see how Quick Sort whizzes through them. Happy sorting and keep exploring the world of algorithms!

--

--

Nikita Babanin

Software engineer exploring tech & productivity. Passionate about coding, balance, and sharing insights. ☕👨‍💻