Course contentsShow
← C
Lesson 1057 of 1,21914. Data Structures in CFree lesson

Quick Sort: Pivot selection

Quick Sort: Pivot selection

What you'll learn: How to choose a "pivot" element to divide a large problem into smaller, manageable chunks.

The Role of the Pivot

Imagine you are a teacher asked to line up 100 students by height. Instead of comparing every student to every other student, you pick one student—let's call him Leo—to stand in the middle. You tell everyone shorter than Leo to move to his left, and everyone taller than Leo to move to his right.

In Quick Sort, Leo is the pivot. The pivot is the benchmark value used to partition an array into two subarrays. Once the partitioning is done, the pivot is in its final, perfectly sorted position, even if the groups on either side are still messy.

Choosing Your Strategy

The efficiency of Quick Sort depends entirely on which element you pick as the pivot. If you pick a pivot that happens to be the median value, you split the work exactly in half, making the algorithm incredibly fast. If you pick the smallest or largest value by mistake, you don't split the work at all, and the sorting takes much longer.

Common strategies include:

  1. First or Last: Picking arr[0] or arr[n-1]. This is simple but risky if the data is already mostly sorted.
  2. Random: Picking a random index to avoid "worst-case" scenarios.
  3. Median-of-Three: Looking at the first, middle, and last elements and picking the one that falls in the middle of those three.

Implementation Example

Here is how you might select the last element as a pivot and use it to rearrange a small array.

#include <stdio.h>

void partitionExample(int arr[], int low, int high) {
    // We choose the last element as the pivot
    int pivot = arr[high]; 
    int i = (low - 1); 

    for (int j = low; j < high; j++) {
        // If current element is smaller than the pivot
        if (arr[j] < pivot) {
            i++;
            // Swap arr[i] and arr[j]
            int temp = arr[i];
            arr[i] = arr[j];
            arr[j] = temp;
        }
    }
    // Finally, swap the pivot into its correct spot
    int temp = arr[i + 1];
    arr[i + 1] = arr[high];
    arr[high] = temp;
}

Why It Matters

A poor pivot choice can turn Quick Sort from a "Formula 1 car" into a "bicycle." By selecting a pivot, you are essentially making a bet on where the middle of your data lies. The goal is always to balance the "left side" and "right side" as evenly as possible to minimize the total number of comparisons.

Key takeaway

The pivot is the "divider" that organizes data; a well-chosen pivot ensures the array is split evenly, maximizing sorting speed.