Quick Sort: Partitioning logic
What you'll learn: How to rearrange an array around a "pivot" element so that smaller values move to the left and larger values move to the right.
The "Divider" Strategy
Quick Sort is a divide-and-conquer algorithm, but all the heavy lifting happens in a step called partitioning. Imagine you have a messy stack of playing cards. You pick one card—let’s say a 7—and call it the pivot.
Your goal isn't to sort the whole deck yet. You just want to move every card smaller than 7 to your left hand and every card larger than 7 to your right hand. Once you're done, the 7 sits perfectly in its final, sorted position. Even if the cards in your left hand (2, 5, 4) aren't in order, you know for a fact they belong somewhere to the left of that 7.
The Hoare Partition Logic
In C, we achieve this using two "scouts" (pointers or indices) that start at opposite ends of the array and run toward each other.
- Pick a Pivot: We usually pick the first, last, or middle element.
- Left Scout: Starts at the beginning and moves right until it finds a value greater than the pivot.
- Right Scout: Starts at the end and moves left until it finds a value smaller than the pivot.
- The Swap: If the scouts haven't met yet, they swap their values and keep moving.
- The Stop: When the scouts cross paths, the array is partitioned.
Seeing it in C
Here is how the partitioning logic looks in code. This function organizes the data and returns the "split point" where the two new groups meet.
#include <stdio.h>
int partition(int arr[], int low, int high) {
int pivot = arr[low]; // Picking the first element as pivot
int i = low - 1;
int j = high + 1;
while (1) {
// Move i to the right as long as elements are smaller than pivot
do { i++; } while (arr[i] < pivot);
// Move j to the left as long as elements are larger than pivot
do { j--; } while (arr[j] > pivot);
// If scouts cross, the partition is complete
if (i >= j) return j;
// Otherwise, swap the misplaced elements
int temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
}
}
By the time this function finishes, the pivot has acted as a border. The array is now two distinct neighborhoods: the "Low" side and the "High" side. Quick Sort simply repeats this process on those smaller neighborhoods until the entire array is aligned.
Key takeaway
Partitioning doesn't fully sort the array; it simply organizes elements into two groups relative to a pivot, ensuring the pivot ends up in its correct mathematical destination.