Sorting Algorithms
Sorting is one of the most studied problems in computer science. In interviews, you'll rarely implement sort from scratch - but understanding how they work helps you choose the right approach and recognize when sorting simplifies a problem.
Quick Reference
# Python's built-in (Timsort) - use this!
nums.sort() # In-place
sorted(nums) # Returns new list
# Custom sort key
nums.sort(key=lambda x: x[1]) # Sort by second element
nums.sort(key=abs) # Sort by absolute value
nums.sort(reverse=True) # Descending
Many problems become trivial after sorting. Two Sum with sorted input? Two pointers. Finding duplicates? Adjacent after sorting. Meeting rooms? Sort by start time. Always ask: would sorting help?
Merge Sort (O(n log n), stable)
Divide, sort halves, merge. Great for linked lists and external sorting.
def mergeSort(arr):
if len(arr) <= 1:
return arr
mid = len(arr) // 2
left = mergeSort(arr[:mid])
right = mergeSort(arr[mid:])
return merge(left, right)
def merge(left, right):
result = []
i = j = 0
while i < len(left) and j < len(right):
if left[i] <= right[j]:
result.append(left[i])
i += 1
else:
result.append(right[j])
j += 1
result.extend(left[i:])
result.extend(right[j:])
return result
Quick Select (O(n) average)
Find kth smallest without fully sorting:
def quickSelect(nums, k):
pivot = nums[len(nums) // 2]
left = [x for x in nums if x < pivot]
mid = [x for x in nums if x == pivot]
right = [x for x in nums if x > pivot]
if k <= len(left):
return quickSelect(left, k)
elif k <= len(left) + len(mid):
return pivot
else:
return quickSelect(right, k - len(left) - len(mid))
Choosing a Sort
- General purpose - Use built-in sort (Timsort)
- Linked list - Merge sort (no random access needed)
- Nearly sorted - Insertion sort (O(n) in best case)
- Find kth element - Quick select (O(n) average)
- Small range integers - Counting sort (O(n + k))
- Need stability - Merge sort or Timsort
Python's sort is stable - equal elements keep their original order. This matters when sorting by multiple keys: sort by secondary key first, then primary.