Quick Sort

Quick Sort Algorithm

Key Takeaways: Quick Sort is one of the fastest and most widely used sorting algorithms. It works by choosing a "pivot" element and moving all smaller elements to its left and larger elements to its right. It uses a "Divide and Conquer" strategy.

Bubble Sort and Selection Sort are very slow for large datasets. If you have millions of items, you need a faster algorithm.

Quick Sort is exactly that. It is heavily used in real-world software because of its incredible speed.


1. The Divide and Conquer Strategy

Quick Sort uses a strategy called Divide and Conquer.

Instead of trying to sort the whole array at once, it breaks the array into smaller, easier-to-sort pieces. It solves the small pieces, and by doing so, the whole array becomes sorted!


2. How Quick Sort Works

Quick Sort relies on a core concept called Partitioning.

Here is the step-by-step process:

  1. Pick a Pivot: Choose one element from the array to be the "pivot" (often the last element).
  2. Partitioning: Rearrange the array so that every number smaller than the pivot is placed on its left. Every number larger than the pivot is placed on its right.
  3. Lock it in: The pivot is now in its exact, final sorted position!
  4. Repeat: Apply the exact same steps to the left sub-array and the right sub-array.
Visual representation of Quick Sort partitioning around a pivot

Partitioning: The pivot (4) moves to the middle. Smaller items go left. Larger items go right.

Because the left and right halves keep getting split into smaller and smaller arrays, the sorting happens incredibly fast.


3. A Step-by-Step Example

Let's sort this array: [8, 2, 5, 3, 9, 4]

Step 1: First Partition

Step 2: Sort the Left Side

Step 3: Sort the Right Side

Final Result: [2, 3, 4, 5, 8, 9]. The whole array is sorted!


4. Quick Sort Code Example

Here is a beginner-friendly Python implementation. Notice how the function calls itself (which is called Recursion).

Quick Sort in Python

def quick_sort(arr):
    # A single item (or empty array) is already sorted!
    if len(arr) <= 1:
        return arr
    # 1. Pick the pivot (we choose the last element)
    pivot = arr[-1]
    # 2. Create arrays for smaller and larger elements
    smaller = []
    larger = []
    # 3. Partition the data
    for i in range(len(arr) - 1):
        if arr[i] < pivot:
            smaller.append(arr[i])
        else:
            larger.append(arr[i])
    # 4. Recursively sort the left and right, then combine!
    return quick_sort(smaller) + [pivot] + quick_sort(larger)

numbers = [8, 2, 5, 3, 9, 4] print("Original:", numbers) print("Sorted:", quick_sort(numbers))


5. Time Complexity


Exercise 1 of 1

?

What happens to the "pivot" element after the partitioning step?