ALGORITHM GUIDE
Quick Sort Algorithm
A simple, visual step-by-step breakdown of the Divide and Conquer sorting strategy.
1. Core Concept
Quick Sort is a highly efficient Divide and Conquer sorting algorithm. It works by selecting a
benchmark element called a pivot, partitioning the surrounding elements into two sub-arrays
according to whether they are smaller or larger than the pivot, and then recursively sorting the sub-
arrays.
Real-World Analogy: Think of lining up people by height. You pick one person as a baseline
(the pivot). You ask everyone shorter to stand on their left and everyone taller to stand on their
right. Then, you repeat this exact same process for the group on the left and the group on the
right until everyone is sorted!
2. Step-by-Step Example
Let's sort this array of numbers step-by-step: [5, 2, 9, 1, 3]
Step 1: Choose a Pivot
We select the last element, 3 , as our pivot.
Step 2: Partition the Array
Group all elements relative to the pivot 3 :
• Smaller than 3: [2, 1]
• Pivot: [3]
• Larger than 3: [5, 9]
Partitioned structure: [2, 1] + [3] + [5, 9]
Page 1 of 3
Step 3: Recurse on Left Sub-array [2, 1]
Pick pivot 1 . Elements smaller: [] , Pivot: [1] , Elements larger: [2] .
Resulting sorted sub-array: [1, 2]
Step 4: Recurse on Right Sub-array [5, 9]
Pick pivot 9 . Elements smaller: [5] , Pivot: [9] , Elements larger: [] .
Resulting sorted sub-array: [5, 9]
Step 5: Combine All Parts
Merge the left, pivot, and right results together:
[1, 2] + [3] + [5, 9] → [1, 2, 3, 5, 9]
3. Time & Space Complexity
Time
Case Explanation
Complexity
Occurs when the pivot splits the array into two equal halves
Best Case O(n log n)
every time.
Average Case O(n log n) The typical performance observed on random input data.
Occurs when the chosen pivot is consistently the smallest or
Worst Case O(n²) largest element (e.g., sorting an already sorted array with last-
element pivot).
Space
O(log n) Space needed for the call stack during recursive execution.
Complexity
4. Key Takeaways
• In-Place Sorting: Quick Sort can be performed in-place with minimal extra memory overhead.
• Cache Friendly: It has excellent spatial locality, making it practically faster than Merge Sort or
Heap Sort on modern hardware.
Page 2 of 3
• Avoiding Worst-Case: To prevent O(n²) behavior, practical implementations use Randomized
Pivot Selection or the Median-of-Three rule.
Page 3 of 3