3 DSA Quick Sort
3 DSA Quick Sort
1. Divide-and-Conquer Approach
Divide: Choose a pivot and partition the array into two halves.
2. Choosing a Pivot
3. Partitioning
4. Recursive Sorting
Once partitioned:
5. Base Case
The recursion terminates when the size of the sub-array is one or zero, as
these are already sorted.
Key Characteristics:
Stability:
o Not Stable: Quick sort is not a stable sort, meaning that equal
elements may not maintain their relative order after sorting.
In-Place:
Comparison-Based:
Adaptive:
o Not Adaptive: Quick sort does not adapt to the order of input
data. Its performance remains consistent regardless of the
input order.
Recursive:
Complexity:
Time Complexity:
o Best Case: O(nlogn) (when the pivot divides the array into
two equal halves)
o Average Case: O(nlogn) (randomly selecting pivots leads to
balanced partitions)
o Worst Case: O(n2) (occurs when the smallest or largest
element is always chosen as the pivot, leading to unbalanced
partitions, e.g., sorted or reverse-sorted input)
Space Complexity:
o Best/Average/Worst Case: O(logn) due to recursive stack
space in typical implementations.
Quick Sort Algorithm Steps
2. Initialize Variables:
o Set j to low - 1.
o Initialize i to low.
3. Choose Pivot:
5. Final Swap:
o After the loop, swap arr[j + 1] and arr[high] to place the pivot
in its correct position.
6. Return: