Quick Sort with Pivot Strategies - Problem
Implement quick sort with three different pivot selection strategies: first element, last element, and median-of-three.
Your task is to sort an array using quick sort and return the sorted array. The pivot strategy determines which element is chosen as the partition pivot during each recursive call.
Pivot Strategies:
first: Always choose the first element as pivotlast: Always choose the last element as pivotmedian-of-three: Choose the median of first, middle, and last elements as pivot
Return the sorted array using the specified pivot strategy.
Input & Output
Example 1 — Basic Array with First Pivot
$
Input:
nums = [3,6,8,2,5], strategy = "first"
›
Output:
[2,3,5,6,8]
💡 Note:
Using first element (3) as pivot repeatedly. First partition puts 2 left of 3, then 5,6,8 right. Continue recursively until sorted.
Example 2 — Same Array with Median-of-Three
$
Input:
nums = [3,6,8,2,5], strategy = "median-of-three"
›
Output:
[2,3,5,6,8]
💡 Note:
Find median of first=3, middle=8, last=5 → median=5. Use 5 as pivot for more balanced partitioning.
Example 3 — Already Sorted with Last Pivot
$
Input:
nums = [1,2,3,4,5], strategy = "last"
›
Output:
[1,2,3,4,5]
💡 Note:
Array already sorted. Last pivot strategy handles this case efficiently by using last element (5) as pivot.
Constraints
- 1 ≤ nums.length ≤ 104
- -106 ≤ nums[i] ≤ 106
- strategy is one of: "first", "last", "median-of-three"
Visualization
Tap to expand
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code