Quick Sort uses the divide-and-conquer technique. It selects a pivot and places it in the correct position, then recursively sorts the left and right subarrays. It's often faster than other simple sorting algorithms.
How We Approach the Problem
To sort an array using Quick Sort, we follow these steps:
- Choose a pivot: Typically the last element of the current subarray.
- Partition the array: Rearrange elements such that all values less than the pivot go to its left, and all values greater go to its right.
- Recursively sort: Apply the same logic to the left and right subarrays.
- Base case: When the subarray has 0 or 1 element, it's already sorted.
Let’s go through an example step-by-step:
Example: [8, 4, 7, 3, 10, 2]
- Choose pivot = 2 (last element)
- Partition: elements less than 2 go to left — none in this case. So 2 is swapped with 8. Now array becomes: [2, 4, 7, 3, 10, 8]
- Now pivot index is 0. Left subarray: [] (empty), Right subarray: [4, 7, 3, 10, 8]
- Repeat the process recursively on right subarray:
- Choose pivot = 8
- Partition left: [4, 7, 3], right: [10]
- Place pivot 8 at index 4
- Repeat recursively on [4, 7, 3] → pivot = 3 → [3, 7, 4]
- Eventually sorted array = [2, 3, 4, 7, 8, 10]
Case 1 - Normal Case with Mixed Elements
This is the typical case where the array has multiple unsorted elements.
- Input: [6, 2, 8, 4, 10]
- Steps:
- Pivot = 10 → partitioned → [6, 2, 8, 4, 10]
- Recursive calls on left part → pivot = 4 → sorted as [2, 4, 6, 8]
- Output: [2, 4, 6, 8, 10]
Case 2 - Already Sorted Array
If the array is already sorted in ascending order, Quick Sort still works, but performance may degrade to O(n²) depending on pivot selection.
- Input: [1, 2, 3, 4, 5]
- Steps: Choosing last element as pivot causes left-heavy recursion.
- Output: [1, 2, 3, 4, 5]
Case 3 - Reverse Sorted Array
This is a worst-case scenario for Quick Sort if the pivot is not selected smartly.
- Input: [5, 4, 3, 2, 1]
- Steps: Each pivot ends up being the smallest → O(n²) recursion.
- Output: [1, 2, 3, 4, 5]
Case 4 - All Elements Equal
If all elements are equal, no real sorting is needed, but the algorithm still makes comparisons.
- Input: [7, 7, 7, 7]
- Steps: Partitioning doesn’t really change order, but recursion continues.
- Output: [7, 7, 7, 7]
Case 5 - Single Element
A single element is trivially sorted.
- Input: [3]
- Steps: Base case — no sorting required.
- Output: [3]
Case 6 - Empty Array
No elements to sort means the result is just an empty array.
- Input: []
- Steps: Base case hit immediately.
- Output: []