MediumArrayDivide and ConquerSortingQuickselect

Quick Sort

LeetCode
1 approach, code in all languages

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
You've got the patterns

Patterns get you through the screen. Shipping gets you hired.

FDE Coach is a cohort-based program in frontend, backend, AWS, and AI where you build real products and get referred to 200+ hiring partners. The free live workshop is the fastest way to see how we teach.

750+ engineers trained · frontend, backend, AWS & AI

August 15 · 0d left
Enroll Now