Quick Sort
1 approach, code in every language
Problem description
Given an integer array nums, rearrange its elements in place so they end up in non-decreasing order, and return the sorted array. As with any sorting exercise here, you should implement the ordering logic yourself rather than calling a library sort.
Quicksort is the divide-and-conquer strategy of choosing a pivot, partitioning the remaining values into those below and those above the pivot, and then sorting each side. Choosing the pivot at random keeps the expected running time at O(n log n) even when the input is already ordered or contains long runs.
Example 1
Input: nums = [9, 3, 7, 1, 8, 2]
Output: [1, 2, 3, 7, 8, 9]
Partitioning around pivots gradually places every value in its final slot.
Example 2
Input: nums = [4, 4, 1, 2]
Output: [1, 2, 4, 4]
Repeated values are handled without issue by the partition step.
Constraints
1 <= nums.length <= 5 * 10^4-5 * 10^4 <= nums[i] <= 5 * 10^4
Create a free account to see the solution
You get the step-by-step animation, the intuition and clean code in every language. Free, no credit card.
After the pattern
Now solve one you haven't seen.
Reading a pattern isn't the same as using it. The practice set has 1,194 original problems on the same techniques, each graded in your browser.
1,194 problems · 15,062 graded tests · free