On this page
Sorting Algorithms
Sorting is a fundamental tool for tackling problems, and is often utilized to help simplify problems.
There are several different sorting algorithms, each with different tradeoffs. In this guide, we will cover several well-known sorting algorithms along with when they are useful.
We will go into detail for merge sort and quick sort, but will describe the rest at a high level.
Terminology
Two commonly used terms in sorting are:
- in-place sort: modifies the input list and does not return a new list
- stable sort: retains the order of duplicate elements after the sort ([3, 2, 4, 2] -> [2, 2, 3, 4])
Merge sort
Merge sort is perhaps the simplest sort to implement and has very consistent behavior. It adopts a divide-and-conquer strategy: recursively sort each half of the list, and then perform an O(N) merging operation to create a fully sorted list.
Implementation
The key operation in merge sort is merge, which is a function that takes two sorted lists and returns a single list which is sorted. It uses two pointers (i and j) to walk through the inputs in lockstep, appending the smaller front element to the result and advancing only that pointer. Once one list is exhausted, the remaining tail of the other is appended.
def merge(list1, list2):
merged = []
i, j = 0, 0
while i < len(list1) and j < len(list2):
if list1[i] <= list2[j]:
merged.append(list1[i])
i += 1
else:
merged.append(list2[j])
j += 1
merged.extend(list1[i:])
merged.extend(list2[j:])
return merged
Every iteration of the loop appends one element to merged and advances exactly one pointer, and the two trailing extend calls together copy the remaining elements once. This makes merge run in O(N) time, where N is the combined length of the inputs. The <= (rather than <) is what makes the sort stable: on a tie, the element from list1 is taken first, so equal-keyed elements that appeared earlier in the input remain earlier in the output. Switching to a strict < would still produce a correctly sorted list, but it would no longer preserve the relative order of equal keys. A recursive implementation will also work, but care is needed to avoid per-call list copies (for example, list1[1:] slicing) which would make each merge O(N2).
Given this merge operation, writing merge sort is quite simple.
def merge_sort(nums):
if len(nums) <= 1:
return nums
middle_idx = len(nums) // 2
left_sorted = merge_sort(nums[:middle_idx])
right_sorted = merge_sort(nums[middle_idx:])
return merge(left_sorted, right_sorted)
Runtime
Merge sort is a recursive, divide and conquer algorithm. It takes O(log N) recursive merge sorts and each merge is O(N) time, so we have a final runtime of O(N log N) for merge sort. Its behavior is consistent regardless of the input list (its worst case and best case take the same amount of time).
Summary
- Worst case: O(N log N)
- Best case: O(N log N)
- Stable: yes
- In-place: no
Quick sort
Quick sort is also a divide and conquer strategy, but uses a two-pointer swapping technique instead of merge. The core idea of quick sort is to select a “pivot” element in the list (the code below uses the first element of the range; choosing the middle element instead avoids the sorted-input worst case described below), and swap elements so that the list splits into a left part whose elements are all less than or equal to the pivot and a right part whose elements are all greater than or equal to it. We call this operation partition. In this two-pointer (Hoare) scheme the pivot can end up anywhere inside its part, which is why both parts, including the returned index, are sorted recursively. Quick sort is notable in its ability to sort efficiently in-place.
def partition(nums, left_idx, right_idx):
pivot = nums[left_idx]
while True:
while nums[left_idx] < pivot and left_idx <= right_idx:
left_idx += 1
while nums[right_idx] > pivot and right_idx >= left_idx:
right_idx -= 1
if left_idx >= right_idx:
return right_idx
nums[left_idx], nums[right_idx] = nums[right_idx], nums[left_idx]
left_idx += 1
right_idx -= 1
The partition function modifies nums inplace and takes up no extra memory. It also takes O(N) time in the worst case to fully partition a list.
def quick_sort_helper(nums, left_idx, right_idx):
if left_idx >= right_idx:
return
pivot_idx = partition(nums, left_idx, right_idx)
if left_idx < pivot_idx:
quick_sort_helper(nums, left_idx, pivot_idx)
if right_idx > pivot_idx + 1:
quick_sort_helper(nums, pivot_idx + 1, right_idx)
def quick_sort(nums):
quick_sort_helper(nums, 0, len(nums) - 1)
Runtime
The best case performance of quick sort is O(N log N), but depending on the structure of the list, quick sort’s performance can vary.
If the pivot happens to be the median of the list, then the list will be divided in half after the partition.
In the worst case, however, the list will be divided into a single-element list and an N - 1 length list. Thus, in the worst possible case, quick sort has O(N2) performance, since we’ll have to recursively quicksort (N - 1), (N - 2), … many lists. However, on average and in practice, quick sort is still very fast due to how fast swapping array elements is.
The space complexity for this version of quick sort comes from the recursion stack. When the partitions are balanced, the calls nest only O(log N) deep, but in the worst case the stack grows to O(N): on an already sorted list, the first-element pivot makes every partition split off a single element, so the recursive calls nest N - 1 deep. To keep the stack at O(log N) even in the worst case, make the recursive call only on the smaller partition and handle the larger partition with a loop in the same call instead of a second recursive call. Making both recursive calls, in either order, still leaves the stack O(N) deep on sorted input.
Summary
- Worst case: O(N2)
- Best case: O(N log N)
- Stable: no
- In-place: yes
Insertion sort
In insertion sort, we incrementally build a sorted list from the unsorted list. We take elements from the unsorted list and insert them into the sorted list, making sure to maintain the order.
This algorithm takes O(N2) worst time, because looping through the unsorted list takes O(N) and finding the proper place to insert can take O(N) time in the worst case. However, if the list is already sorted, insertion sort takes O(N) time, since insertion time will be O(1). Insertion sort can be done in-place, so it takes up O(1) space.
Insertion sort is easier on linked lists, which have O(1) insertion whereas arrays have O(N) insertion because in an array, inserting an element requires shifting all the elements behind that element.
Summary
- Worst case: O(N^2)
- Best case: O(N)
- Stable: yes
- In-place: yes
Selection sort
Selection sort incrementally builds a sorted list by finding the minimum value in the rest of the list, and swapping it to be in the front.
It takes O(N2) time in general, because we have to loop through the unsorted list which is O(N) and in each iteration, we search the rest of the list which always takes O(N). Selection sort can be done in-place, so it takes up O(1) space.
Summary
- Worst case: O(N2)
- Best case: O(N2)
- Stable: no
- In-place: yes
Radix sort
Radix sort is a situational sorting algorithm when you know that the numbers you are sorting are bounded in some way. It operates by grouping numbers in the list by digit, looping through the digits in some order.
For example, if we had the list [100, 10, 1], radix sort would put 100 in the group which had 1 in the 100s digit place and would put (10, 1) in a group which had 0 in the 100s digit place. It would then sort by the 10s digit place, and finally the 1s digit place.
Radix sort thus needs one pass for each digit place it is sorting and takes O(KN) time, where K is the number of passes necessary to cover all digits.
Summary
- Worst case: O(KN)
- Best case: O(KN)
- Stable: yes (if going through digits from right to left)
- In-place: no
References
- Merge Sort (iterative approach shown)
- Pivoting to Understand Quicksort