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 pivot
  • last: Always choose the last element as pivot
  • median-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
INPUT ARRAYPIVOT STRATEGIESSORTED RESULT36825Original unsorted arrayLength: 5 elements1First ElementAlways choose arr[0] as pivot2Last ElementAlways choose arr[n-1] as pivot3Median-of-ThreeChoose median of first, middle, lastBest Performance:Median-of-three avoidsworst-case on sorted data23568Final sorted array[2, 3, 5, 6, 8]Time Complexity:Average: O(n log n)Worst: O(n²)Space Complexity:O(log n) recursion stackKey Insight:Pivot selection strategy significantly impacts performance - median-of-three providesthe best balance by creating more even partitions and avoiding worst-case scenarios.TutorialsPoint - Quick Sort with Pivot Strategies | Comparison
Asked in
Google 25 Amazon 18 Microsoft 15 Apple 12
23.4K Views
Medium Frequency
~25 min Avg. Time
890 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen