Given an array of integers nums, sort it in ascending order using a quicksort-based approach and return the sorted array.
Your implementation must use the median-of-three pivot strategy to avoid O(n^2) worst-case performance on sorted or nearly sorted inputs. Median-of-three selects the pivot as the median of the first, middle and last elements of the current subarray. The exercise is the quicksort itself, so calling a library sort does not meet the requirement.
Function Signature
def sort_array(nums: list[int]) -> list[int]:
Rules
-
Keep every element, including duplicates. The output has the same length as the input.
-
For a subarray
nums[lo..hi]
, the middle element is the one at index
lo + (hi - lo) // 2
.
-
You may sort
nums
in place and return it, or return a new list.
-
Switching to insertion sort for very short subarrays is allowed.
Constraints
-
1 <= len(nums) <= 5 * 10^4
-
-5 * 10^4 <= nums[i] <= 5 * 10^4
Examples
Input: nums = [5, 2, 3, 1]
Output: [1, 2, 3, 5]
These are the four input values in ascending order.
Input: nums = [5, 1, 1, 2, 0, 0]
Output: [0, 0, 1, 1, 2, 5]
Both copies of 0 and both copies of 1 stay in the output, so it holds the same six elements as the input.
Input: nums = [9, 8, 7, 6, 5, 4, 3, 2, 1, 0, -1, -2]
Output: [-2, -1, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
The input is reverse sorted. A first-element or last-element pivot would split off only one element per partition here. The median of 9, 4 and -2 is 4, and six of the other values are smaller than 4 while five are larger, so the first split is close to even.