Introduction
Quick Sort is one of the fastest and most widely used sorting algorithms.
It is based on:
Divide and ConquerThe idea is:
- Choose a pivot element
- Place pivot in correct position
- Move smaller elements left
- Move larger elements right
- Recursively sort both halves
This problem helps in understanding:
- recursion
- partitioning
- divide and conquer
- in-place sorting
Example
Input:arr = [10, 7, 8, 9, 1, 5]
Output:
[1, 5, 7, 8, 9, 10]
Explanation:
Pivot divides array into smaller and larger elements during every recursive call.
Constraints
1 <= arr.length <= 10^5-10^9 <= arr[i] <= 10^9Approach : Divide and Conquer
Explanation
Quick Sort works in three steps:
- Choose Pivot
- usually last element
- Partition Array
- smaller elements left
- larger elements right
- Recursively Sort
- left half
- right half
Partitioning is the key operation.
Steps
- Select pivot element.
- Partition array.
- Place pivot correctly.
- Recursively sort left side.
- Recursively sort right side.
- Return sorted array.
Dry Run
Input:[10, 7, 8, 9, 1, 5]
Pivot:
5
Partition:
[1] 5 [10, 7, 8, 9]
Pivot fixed at correct position
Recursively sort:
[1] and [10, 7, 8, 9]
Next pivot: 9
Partition:
[7, 8] 9 [10]
Continue recursion...
Final Result:
[1, 5, 7, 8, 9, 10]
Quick Sort Code
Complexity Analysis
ort helps in understan
Best Case Time Complexity: O(n log n)
Average Case Time Complexity: O(n log n)
Worst Case Time Complexity: O(n²)
Explanation:
Worst case occurs when pivot selection becomes poor.
Space Complexity: O(log n)
Explanation:
Recursive stack space is used.
Edge Cases
- Empty array
- Single element array
- Already sorted array
- Reverse sorted array
- Duplicate elements present
Why This Problem is Important
Quick Sort helps in understanding:
- Divide and Conquer
- Partitioning techniques
- Recursion
- In-place sorting
- Pivot optimization
It is one of the most important advanced sorting algorithms.
Real-World Applications
Quick Sort concepts are used in:
- Standard library sorting
- Database systems
- Search engines
- Large-scale data processing
- Operating systems
Common Mistakes
- Incorrect partition logic
- Wrong pivot placement
- Infinite recursion
- Incorrect recursive boundaries
Interview Tips
Interviewers often expect:
- Partition explanation
- Divide and Conquer understanding
- Average vs worst case analysis
Always explain:
- pivot selection
- partition process
- recursive sorting separately
Related Questions
- Merge Sort
- Heap Sort
- Kth Largest Element
- Sort Colors
- Quick Select
Final Takeaway
Quick Sort is a fundamental divide-and-conquer sorting algorithm that teaches partitioning and recursive sorting techniques. Understanding Quick Sort builds a strong foundation for advanced sorting algorithms and interview problems.