Definition
Quick sort is a sorting algorithm that divides an array into smaller subarrays based on a pivot element. Quick sort selects a pivot, then partitions the array so that elements less than the pivot are on its left and elements greater than the pivot are on its right. The algorithm then recursively sorts the subarrays on either side of the pivot until the entire array is ordered. If a subarray has zero or one elements, it is already sorted and requires no further partitioning.
Constraints
- Performance depends heavily on pivot selection, as a bad pivot can degrade efficiency
- Not ideal for linked lists due to slow random access and poor cache performance during partitioning
- Recursive implementation can lead to stack overflow for very large arrays due to deep recursion
Step-by-step explanation
Arguments:
- Array to be sorted -
array - Starting index -
low - Ending index -
high - Pivot element -
pivot - Left partition (elements ≤ pivot) -
left - Right partition (elements > pivot) -
right
Explanation:
- Select a pivot element from the array, typically
array[high]or a random index - Partition the array into two subarrays around the pivot:
- Elements less than the pivot go to the left of
pivot - Elements greater than the pivot go to the right of
pivot - Recursively apply QuickSort to the left subarray
array[low..pivotIndex - 1] - Recursively apply QuickSort to the right subarray
array[pivotIndex + 1..high] - Repeat until subarrays have 0 or 1 element (base case)
Returns:
Returns nothing (sorts array in-place)
Modifies the original array instead of returning a new one
No explicit return value (void function in most implementations)