Implement quick sort with Hoare
Standard · Write code · about 20 min
Sort nums in ascending order with quick sort and the Hoare partition. The pivot is the first value. i walks right and j walks left, and out-of-place pairs swap until the pointers meet.
Sort in place and return the same array.
Example 1
Input:
[[5,2,8,1,9,4]]
Output:
[1,2,4,5,8,9]
Example 2
Input:
[[2,1]]
Output:
[1,2]
Example 3
Input:
[[4,4,4]]
Output:
[4,4,4]
Equal values stop both pointers and swap.
Constraints
- 0 ≤ nums.length ≤ 1,000
- -1,000 ≤ nums[i] ≤ 1,000
- Sort in place and return the same array
Learn the idea first: Quick sort: partitioning and pivots, a visual lesson.
More Quick sort: partitioning and pivots problems
- Partition by hand Warm-up
- Fill in the Lomuto partition Warm-up
- Implement quick sort with Lomuto Standard
- Spot the bug: the scan stops early Standard
- Sort colors (Dutch national flag) Challenge