Note Time: O(n^2) all cases. Space: O(1). NOT stable (swapping can change relative order of equal elements). Minimizes the number of swaps (at most n-1), which can matter when writes are expensive.
Pick a pivot.Partition: elements < pivot go left,>= pivot go right.Recursively sort left and right partitions.
Example
// JavaScriptfunctionquickSort(arr, lo =0, hi = arr.length-1){if(lo >= hi)return arr;const pivotIdx =partition(arr, lo, hi);quickSort(arr, lo, pivotIdx -1);quickSort(arr, pivotIdx +1, hi);return arr;}functionpartition(arr, lo, hi){const pivot = arr[hi];let i = lo;for(let j = lo; j < hi; j++){if(arr[j]< pivot){[arr[i], arr[j]]=[arr[j], arr[i]];
i++;}}[arr[i], arr[hi]]=[arr[hi], arr[i]];return i;}
# Python
def quick_sort(arr, lo=0, hi=None):if hi isNone:
hi =len(arr)-1if lo >= hi:return arr
pivot_idx =partition(arr, lo, hi)quick_sort(arr, lo, pivot_idx -1)quick_sort(arr, pivot_idx +1, hi)return arr
def partition(arr, lo, hi):
pivot = arr[hi]
i = lo
for j inrange(lo, hi):if arr[j]< pivot:
arr[i], arr[j]= arr[j], arr[i]
i +=1
arr[i], arr[hi]= arr[hi], arr[i]return i
Output
quick_sort([10,7,8,9,1,5]) → [1,5,7,8,9,10]
Note Time: O(n log n) avg, O(n^2) worst (already sorted with bad pivot). Space: O(log n) avg stack. NOT stable. Randomizing the pivot avoids worst case. In practice, quicksort is often faster than merge sort due to cache locality. Lomuto partition (shown) is simpler; Hoare partition is faster.
Frequently asked questions
How does Interview Prep handle in-place sort?
Interview Prep covers this with 2 copy-ready snippets on this page. The "Selection Sort" snippet in Interview Prep uses `Find the minimum element in the unsorted portion.`.
Which code does the Interview Prep example use?
The "Selection Sort" snippet uses `Find the minimum element in the unsorted portion.`, from the Sorting section of the Interview Prep cheat sheet.
What other Interview Prep snippets are shown for "in-place sort"?
Besides "Selection Sort", this page also shows "Quick Sort".
Is there anything to watch out for?
Yes. For "Selection Sort": Time: O(n^2) all cases. Space: O(1). NOT stable (swapping can change relative order of equal elements). Minimizes the number of swaps (at most n-1), which can matter when writes are expensive.