π Sorting & Searching Algorithms
in Python
Learn sorting and searching in Python: bubble, selection, insertion, merge and quick sort, sorted() and key, stability, binary search and bisect, with Big-O comparisons.
What this lesson is about
Sorting and searching are the two oldest problems in programming, and they are still everywhere. Every time you see a leaderboard, an alphabetised contact list, a table sorted by price or a search result that appears instantly, a sorting or searching algorithm is doing the work. They are also the best place to learn how to compare algorithms, because the same task can be solved in ways whose speeds differ by orders of magnitude.
In daily Python you will almost always call the built-in sorted() or list.sort(), which are fast, stable and carefully engineered. So why learn the classic algorithms? Because they teach you how to think about cost, because interviews still ask about them, and because ideas such as divide and conquer, partitioning and halving the search space turn up again in many other problems. Understanding what the built-in is doing for you also helps you use key=, stability and bisect properly.
This lesson goes from the simple quadratic sorts (bubble, selection, insertion) to the efficient ones (merge sort and quicksort), then to Python's own tools, then to searching: linear search, binary search and the bisect module. Each example prints what happens along the way, including counts of comparisons, so you can see the cost and not just be told about it. Read Big-O alongside this page if the notation is new, and look at recursion for the divide-and-conquer pieces.
What you will learn
- βWrite bubble, selection and insertion sort and explain why each is O(n squared)
- βImplement merge sort and watch the merge step combine sorted halves
- βImplement quicksort with partitioning and understand its worst case
- βUse
sorted(),list.sort(),key=andreverse=correctly - βExplain what a stable sort is and use it for multi-level sorting
- βWrite binary search and its boundary variants without off-by-one errors
- βUse the
bisectmodule for lookups and for inserting into sorted lists - βCompare algorithms by counting operations instead of guessing
Why programmers should learn this
- β Sorted data makes many other problems easy: duplicates sit side by side, ranges can be found by binary search, and merging two sorted lists is linear.
- β Knowing why quadratic algorithms collapse on large inputs helps you spot slow code in real programs before it reaches production.
- β Binary search is the model for any 'halve the problem' technique, from searching databases to finding a bug with git bisect.
- β
Python's
key=and stable sorting let you express complicated orderings, such as 'by department, then by salary descending', in a few clear lines. - β Sorting and searching questions are a staple of technical interviews, and the reasoning about invariants and boundaries carries over to everything else.
Bubble, selection and insertion sort
The three elementary sorts all take O(n squared) time in the typical case, because they use two nested loops over the data. They are worth knowing because they are short, they show different ways of building a sorted list, and one of them (insertion sort) is genuinely useful on small or almost-sorted inputs.
Bubble sort sweeps through the list repeatedly, swapping neighbours that are in the wrong order, so the largest value 'bubbles' to the end on the first pass. Selection sort finds the smallest remaining value on each pass and swaps it into position, so it always does about n squared over two comparisons, but only n swaps. Insertion sort treats the left part of the list as already sorted and slides each new value backwards into place, like sorting playing cards in your hand. On data that is already nearly sorted it does very little work, close to O(n).
I instrumented each function to count comparisons and then ran them on the same input. Look at how the numbers differ even though the three algorithms share the same big-O class. Constant factors and the shape of the input matter.
def bubble_sort(items):
a = list(items)
comparisons = 0
for end in range(len(a) - 1, 0, -1):
swapped = False
for i in range(end):
comparisons += 1
if a[i] > a[i + 1]:
a[i], a[i + 1] = a[i + 1], a[i]
swapped = True
if not swapped:
break
return a, comparisons
def selection_sort(items):
a = list(items)
comparisons = 0
for i in range(len(a) - 1):
smallest = i
for j in range(i + 1, len(a)):
comparisons += 1
if a[j] < a[smallest]:
smallest = j
a[i], a[smallest] = a[smallest], a[i]
return a, comparisons
def insertion_sort(items):
a = list(items)
comparisons = 0
for i in range(1, len(a)):
value = a[i]
j = i - 1
while j >= 0:
comparisons += 1
if a[j] <= value:
break
a[j + 1] = a[j]
j -= 1
a[j + 1] = value
return a, comparisons
data = [7, 3, 9, 1, 8, 2, 6, 5]
nearly = [1, 2, 3, 5, 4, 6, 7, 8]
for name, fn in [("bubble", bubble_sort), ("selection", selection_sort), ("insertion", insertion_sort)]:
out, c1 = fn(data)
_, c2 = fn(nearly)
print(f"{name:9} {out} shuffled={c1:2} nearly sorted={c2:2}")bubble [1, 2, 3, 5, 6, 7, 8, 9] shuffled=25 nearly sorted=13 selection [1, 2, 3, 5, 6, 7, 8, 9] shuffled=28 nearly sorted=28 insertion [1, 2, 3, 5, 6, 7, 8, 9] shuffled=21 nearly sorted= 8
Line by line
- 1-13Bubble sort. Each outer pass shrinks the unsorted region by one because the largest value has landed at the end. If a whole pass makes no swap, the list is sorted and we stop early.
- 15-25Selection sort. For each position
iwe scan the rest to find the smallest value, then swap it into place. The scan always happens, so the comparison count never improves. - 27-40Insertion sort. Take
a[i], shift larger values one step to the right, and drop the value into the gap. Thebreakstops as soon as the value meets a smaller or equal neighbour. - 42-47Run each sort on a shuffled list and a nearly sorted list and compare the number of comparisons.
Insertion sort is the one to remember. Real-world hybrid sorts, including Python's own, use it on tiny runs of data because it has so little overhead.
Merge sort: divide and conquer
Merge sort is the first of the efficient algorithms and the cleanest example of divide and conquer. Split the list in half, sort each half recursively, then merge the two sorted halves into one sorted list. A list of length one is already sorted, which is the base case. If you are not yet comfortable with that style of thinking, recursion covers it step by step.
The real work happens in the merge. Keep one pointer at the front of each half, compare the two front values, copy the smaller one to the output and advance that pointer. When one half runs out, copy whatever remains of the other. Because both halves are already sorted, this takes a single pass through them: O(n) per merge.
The list is halved about log n times and each level of the recursion does O(n) merge work in total, so merge sort runs in O(n log n) in every case: best, average and worst. The price is O(n) of extra memory for the merged lists. It is also stable: when two values are equal, the one from the left half goes first, so equal elements keep their original order. I print each merge so you can watch it build up.
def merge(left, right):
out, i, j = [], 0, 0
while i < len(left) and j < len(right):
if left[i] <= right[j]: # <= keeps the sort stable
out.append(left[i])
i += 1
else:
out.append(right[j])
j += 1
out.extend(left[i:])
out.extend(right[j:])
return out
def merge_sort(items, depth=0):
if len(items) <= 1:
return items
mid = len(items) // 2
left = merge_sort(items[:mid], depth + 1)
right = merge_sort(items[mid:], depth + 1)
merged = merge(left, right)
print(" " * depth + f"merge {left} + {right} -> {merged}")
return merged
print(merge_sort([38, 27, 43, 3, 9, 82, 10])) merge [27] + [43] -> [27, 43]
merge [38] + [27, 43] -> [27, 38, 43]
merge [3] + [9] -> [3, 9]
merge [82] + [10] -> [10, 82]
merge [3, 9] + [10, 82] -> [3, 9, 10, 82]
merge [27, 38, 43] + [3, 9, 10, 82] -> [3, 9, 10, 27, 38, 43, 82]
[3, 9, 10, 27, 38, 43, 82]Line by line
- 1-11
mergewalks two sorted lists with two indexes, always taking the smaller front value. Using<=means that on a tie the left value goes first, which is what makes the algorithm stable. - 9-10After the loop, at most one list still has values. Appending both leftovers is safe because an empty slice adds nothing.
- 13-21
merge_sortsplits at the middle, sorts each half recursively and merges the results. Thedepthargument only exists to indent the printed trace. - 23Sort seven numbers and watch the merges happen from the smallest pieces upward.
The trace prints the innermost merges first, because the recursion has to finish sorting the halves before any merge can happen. That is the order in which the work is really done.
Quicksort and partitioning
Quicksort is another divide-and-conquer algorithm, but it does its work before the recursion instead of after. Pick a pivot value, partition the list into values smaller than the pivot, equal to it and larger than it, then sort the smaller and larger groups recursively. Once the recursion finishes the pieces simply join together, because everything on the left is already smaller than everything on the right.
On average quicksort runs in O(n log n), and it is often the fastest comparison sort in practice because it is cache friendly and the in-place version needs very little extra memory. Its weakness is the worst case. If the pivot is always the smallest or largest value, as happens when you always choose the first element of an already sorted list, each partition removes only one element and the running time drops to O(n squared). Good implementations choose pivots more carefully, for example the median of three values, or randomly.
The version below favours clarity over speed: it builds new lists with comprehensions rather than partitioning in place, and uses the middle element as the pivot. I count the recursive calls so that you can see how the pivot choice changes the amount of work, on random-looking data versus data that is already sorted when the pivot is always the first item.
import random
calls = 0
def quicksort(items, pick):
global calls
calls += 1
if len(items) <= 1:
return items
pivot = pick(items)
smaller = [x for x in items if x < pivot]
equal = [x for x in items if x == pivot]
larger = [x for x in items if x > pivot]
return quicksort(smaller, pick) + equal + quicksort(larger, pick)
middle = lambda items: items[len(items) // 2]
first = lambda items: items[0]
rng = random.Random(3)
shuffled = list(range(200))
rng.shuffle(shuffled)
already_sorted = list(range(200))
print(quicksort([9, 4, 7, 1, 8, 2, 6], middle))
for label, data, pick in [("shuffled, middle pivot", shuffled, middle),
("sorted, middle pivot", already_sorted, middle),
("sorted, first pivot", already_sorted, first)]:
calls = 0
result = quicksort(data, pick)
assert result == sorted(data)
print(f"{label:24} recursive calls: {calls}")[1, 2, 4, 6, 7, 8, 9] shuffled, middle pivot recursive calls: 275 sorted, middle pivot recursive calls: 255 sorted, first pivot recursive calls: 399
Line by line
- 3A global counter so we can compare how much work each configuration does.
- 5-13The core. Choose a pivot, split into three lists with comprehensions, sort the smaller and larger parts and join them around the equal values.
- 15-16Two pivot strategies written as small functions: the middle element and the first element.
- 18-21Build the test data: a shuffled list (seeded so it is repeatable) and an already sorted list.
- 23A small demonstration that the function returns a sorted list.
- 25-31Count the recursive calls for three cases and use
assertto check each result against the built-insorted.
The middle pivot copes with sorted input perfectly, but the first-element pivot is the trap: it needs hundreds of calls where a good choice needs only a few hundred more than the input size. Keeping the equal values in their own list also avoids a different slow case, where many duplicates would otherwise keep landing on one side.
Python's sorted(), list.sort(), key and stability
In real programs, use the built-ins. sorted(iterable) returns a new list and works on any iterable, while list.sort() sorts a list in place and returns None. Both use Timsort, a hybrid of merge sort and insertion sort designed to exploit runs of already-ordered data. It runs in O(n log n) in the worst case and close to O(n) on data that is already sorted or nearly so, and it needs up to O(n) extra memory.
The most important argument is key=. It is a function that is called once for each element, and the elements are ordered by the values it returns. This is far better than the old comparison-function approach, because it is faster and easier to read. reverse=True flips the order. Common keys are len, str.lower, abs, operator.itemgetter or a lambda that returns a tuple. A tuple key sorts by the first item, then the second for ties.
Python's sort is stable: elements that compare equal keep their original relative order. That property lets you sort in several passes. To order by department and then by name within each department, sort by name first and then sort again by department; the second sort leaves names in order inside each department. The example shows both the tuple-key shortcut and the two-pass trick.
people = [
("Mia", "Sales", 52),
("Omar", "Dev", 61),
("Lena", "Dev", 58),
("Ravi", "Sales", 52),
("Zoe", "Ops", 47),
]
print(sorted([3, -7, 5, -1], key=abs))
print(sorted(["banana", "Apple", "cherry"]))
print(sorted(["banana", "Apple", "cherry"], key=str.lower))
print(sorted(["pear", "fig", "banana", "kiwi"], key=len))
# tuple key: department ascending, salary descending
by_tuple = sorted(people, key=lambda p: (p[1], -p[2]))
print([p[0] for p in by_tuple])
# stability: ties keep their original order
by_salary = sorted(people, key=lambda p: p[2])
print([p[0] for p in by_salary])
# two passes: name first, then department
step1 = sorted(people, key=lambda p: p[0])
step2 = sorted(step1, key=lambda p: p[1])
print([p[0] for p in step2])
nums = [5, 2, 8]
result = nums.sort()
print(result, nums)[-1, 3, 5, -7] ['Apple', 'banana', 'cherry'] ['Apple', 'banana', 'cherry'] ['fig', 'pear', 'kiwi', 'banana'] ['Omar', 'Lena', 'Zoe', 'Mia', 'Ravi'] ['Zoe', 'Mia', 'Ravi', 'Lena', 'Omar'] ['Lena', 'Omar', 'Zoe', 'Mia', 'Ravi'] None [2, 5, 8]
Line by line
- 1-7Records of name, department and salary. Mia and Ravi share a salary of 52 on purpose.
- 9
key=abssorts by absolute value, but the original numbers are returned. - 10-11The default string sort is case-sensitive, so uppercase
Applecomes before lowercase letters;key=str.lowerfixes that. - 12Sort strings by length.
pearandkiwiare tied, andpearstays first because the sort is stable. - 14-16A tuple key sorts by department, then breaks ties by negative salary, which means highest salary first.
- 18-20Sorting by salary alone: Mia and Ravi are equal, and the output shows Mia before Ravi, the same order as the input.
- 22-25Two-pass sorting that relies on stability: by name, then by department.
- 27-29
list.sort()changes the list and returnsNone, a frequent source of bugs.
Writing nums = nums.sort() leaves nums set to None. Use nums.sort() on its own line or nums = sorted(nums).
Linear search and binary search
Linear search checks items one by one until it finds the target. It works on any list, sorted or not, and costs O(n). That is perfectly fine for short lists or when you search only once.
Binary search needs a sorted list and uses it to throw away half of the remaining candidates on every step. Look at the middle element. If it equals the target you are done; if the target is smaller, the answer can only be in the left half; if larger, only the right half. Searching a million sorted items takes at most about twenty steps, since 2 to the power of 20 is just over a million. That is O(log n), explained in Big-O.
Binary search is famous for off-by-one errors, so I use a consistent convention: lo and hi are the inclusive bounds of the region that could still hold the target. The loop continues while lo <= hi, and each branch moves a bound past mid, never onto it, which guarantees the region shrinks. The code returns the index, or -1 when the target is absent, and prints the region at every step so you can follow the halving.
def linear_search(items, target):
for i, value in enumerate(items):
if value == target:
return i, i + 1
return -1, len(items)
def binary_search(items, target, trace=False):
lo, hi = 0, len(items) - 1
steps = 0
while lo <= hi:
steps += 1
mid = (lo + hi) // 2
if trace:
print(f" lo={lo} hi={hi} mid={mid} value={items[mid]}")
if items[mid] == target:
return mid, steps
if items[mid] < target:
lo = mid + 1
else:
hi = mid - 1
return -1, steps
data = list(range(3, 100, 3)) # 3, 6, 9, ... 99
print(data[:6], "... length", len(data))
print("search 51:")
print(binary_search(data, 51, trace=True))
print("search 52:")
print(binary_search(data, 52, trace=True))
print("linear for 99:", linear_search(data, 99))
print("binary for 99:", binary_search(data, 99))[3, 6, 9, 12, 15, 18] ... length 33 search 51: lo=0 hi=32 mid=16 value=51 (16, 1) search 52: lo=0 hi=32 mid=16 value=51 lo=17 hi=32 mid=24 value=75 lo=17 hi=23 mid=20 value=63 lo=17 hi=19 mid=18 value=57 lo=17 hi=17 mid=17 value=54 (-1, 5) linear for 99: (32, 33) binary for 99: (32, 6)
Line by line
- 1-5Linear search returns the index and how many items it looked at.
- 7-20Binary search.
loandhibracket the region that could still contain the target. We look atmid, then moveloabove it orhibelow it, so the region always shrinks. - 12-13Optional tracing so we can see the bounds.
- 22-23Thirty-three values, each a multiple of three.
- 25-29Search for a present value and an absent one. The trace shows the search area halving each time. Missing values end when
lopasseshi. - 31-32The same target near the end: linear search needs to check every item, while binary search needs only a handful.
Binary search only works on sorted data. On unsorted input it silently returns wrong answers, because the 'discard half' step is no longer justified.
The bisect module
Python ships binary search in the standard library as bisect. Instead of just finding an exact match, bisect_left(a, x) returns the leftmost position where x could be inserted while keeping the list sorted, and bisect_right(a, x) returns the position after any existing copies of x. The difference between those two answers tells you how many copies exist, and both run in O(log n).
That makes bisect ideal for tasks that are awkward to write by hand: counting how many values fall in a range, finding the first value greater than a threshold, or mapping numbers to categories. A classic use is turning scores into letter grades using a list of breakpoints. bisect.insort(a, x) inserts while keeping order. The search is O(log n) but shifting list elements to make room is O(n), so for heavy insertion workloads a heap or a different structure may serve better.
Since Python 3.10 both functions accept a key= argument as well, which lets you search a list of records by one field without building a separate list. In the example I use plain numbers for the first demonstrations and a small record list for the last.
import bisect
a = [10, 20, 20, 20, 30, 40]
print("left of 20 :", bisect.bisect_left(a, 20))
print("right of 20:", bisect.bisect_right(a, 20))
print("copies of 20:", bisect.bisect_right(a, 20) - bisect.bisect_left(a, 20))
print("left of 25 :", bisect.bisect_left(a, 25))
# how many values fall in [20, 40)?
print("in [20,40):", bisect.bisect_left(a, 40) - bisect.bisect_left(a, 20))
# map a score to a grade with breakpoints
def grade(score, breakpoints=(60, 70, 80, 90), letters="FDCBA"):
return letters[bisect.bisect(breakpoints, score)]
print([grade(s) for s in (55, 60, 69, 70, 85, 90, 100)])
# keep a list sorted while inserting
live = []
for x in [42, 7, 19, 3, 25]:
bisect.insort(live, x)
print("after", x, "->", live)
# key= searches records by one field
records = [("ann", 21), ("bo", 30), ("cy", 35), ("di", 48)]
i = bisect.bisect_left(records, 33, key=lambda r: r[1])
print("first record aged 33+:", records[i])left of 20 : 1
right of 20: 4
copies of 20: 3
left of 25 : 4
in [20,40): 4
['F', 'D', 'D', 'C', 'B', 'A', 'A']
after 42 -> [42]
after 7 -> [7, 42]
after 19 -> [7, 19, 42]
after 3 -> [3, 7, 19, 42]
after 25 -> [3, 7, 19, 25, 42]
first record aged 33+: ('cy', 35)Line by line
- 1-7On a list with three copies of 20: the left position is where the first 20 sits, the right position is just after the last one, and the difference is the number of copies. 25 would be inserted at index 4.
- 9-10Counting values in a half-open range is two bisects subtracted.
- 12-16Breakpoints for grades.
bisectreturns how many breakpoints are less than or equal to the score, which is exactly the index of the letter. - 18-22
insortkeeps the list sorted after each insertion. - 24-27The
key=argument (Python 3.10 and later) is applied to the list elements while the target is compared as given.
If you only need the smallest or largest items repeatedly, a heap from heapq is usually a better fit than keeping a list sorted. You will see that idea in trees and graphs with Dijkstra and again in the interview patterns lesson.
Comparing algorithms by counting
Big-O tells you how cost grows; counting operations shows it. Instead of timing the code, which varies between machines and is not repeatable, I count comparisons. That gives deterministic numbers that anyone running the page will see.
Doubling the input size is a good experiment. A quadratic algorithm should need about four times as many comparisons when n doubles, while an O(n log n) algorithm needs slightly more than double. The code runs insertion sort and a counting version of merge sort on seeded random lists of increasing size and prints the ratio between consecutive sizes.
You should see insertion sort's counts roughly quadruple while merge sort's counts a little more than double. Remember what this does not capture: for very small lists simple sorts can beat complicated ones because of lower overhead, which is why Timsort starts with insertion sort on small runs. And for anything you ship, sorted() will beat both of my hand-written versions, because it is implemented in C.
import random
def insertion_count(items):
a, count = list(items), 0
for i in range(1, len(a)):
value, j = a[i], i - 1
while j >= 0:
count += 1
if a[j] <= value:
break
a[j + 1] = a[j]
j -= 1
a[j + 1] = value
return count
def merge_count(items):
count = 0
def sort(a):
nonlocal count
if len(a) <= 1:
return a
mid = len(a) // 2
left, right = sort(a[:mid]), sort(a[mid:])
out, i, j = [], 0, 0
while i < len(left) and j < len(right):
count += 1
if left[i] <= right[j]:
out.append(left[i]); i += 1
else:
out.append(right[j]); j += 1
return out + left[i:] + right[j:]
sort(list(items))
return count
rng = random.Random(11)
prev = None
print(f"{'n':>6} {'insertion':>10} {'merge':>8} growth (insertion, merge)")
for n in (250, 500, 1000, 2000):
data = [rng.randrange(10**6) for _ in range(n)]
ins, mer = insertion_count(data), merge_count(data)
growth = "" if prev is None else f"x{ins / prev[0]:.1f}, x{mer / prev[1]:.1f}"
print(f"{n:>6} {ins:>10} {mer:>8} {growth}")
prev = (ins, mer)n insertion merge growth (insertion, merge) 250 16189 1667 500 60839 3864 x3.8, x2.3 1000 251962 8716 x4.1, x2.3 2000 1031982 19428 x4.1, x2.2
Line by line
- 3-14Insertion sort again, returning only the number of comparisons.
- 16-34A merge sort that counts every comparison made while merging.
nonlocallets the inner function update the outercount. - 36-38A seeded random generator, so the same data is produced on every run.
- 39-45For each size, generate random data and count comparisons, then print how much each count grew compared with the previous, smaller size.
Whenever you are unsure which approach is faster, measure operations on realistic data. Counting is repeatable, and the shape of the growth is what predicts how the code behaves at ten times the size.
Common mistakes
β Assigning the result of list.sort()
list.sort() sorts in place and returns None. Writing data = data.sort() throws your list away. Use sorted(data) when you want a new list.
β Running binary search on unsorted data
The algorithm assumes order. On unsorted input it can skip over the target and report that it is missing. Sort first or use a set or dictionary instead.
β Off-by-one errors in the bounds
Mixing inclusive and exclusive bounds, or using lo < hi with hi = mid - 1, can skip the last candidate or loop forever. Pick one convention and move each bound past mid.
β Writing a comparison function by hand
Python 3 sorts with key=, which is faster and shorter than comparing pairs. If you really need a comparator, functools.cmp_to_key adapts one.
β Choosing quicksort's pivot badly
Always taking the first or last element makes sorted input hit the O(n squared) worst case. Use the middle, a median of three or a random pivot.
Quick quiz
Tap an answer. I explain every one, right or wrong.
Q1. Which sorting algorithm always takes O(n log n) time and is stable?
Q2. What does sorted(words, key=len) do when two words have the same length?
Q3. What is the worst-case time of binary search on a sorted list of n items?
Q4. For a = [1, 2, 2, 3], what does bisect.bisect_right(a, 2) return?
bisect_right returns the insertion point after the last 2, which is index 3. bisect_left would return 1.Q5. What is printed by print([3, 1, 2].sort())?
list.sort() changes the list in place and returns None.Q6. Why does quicksort with a first-element pivot perform badly on already sorted input?
Frequently asked questions
Which sorting algorithm does Python use?
+sorted() and list.sort() use Timsort, a stable hybrid of merge sort and insertion sort that takes advantage of existing ordered runs. It is O(n log n) in the worst case and close to linear on nearly sorted data.
When should I write my own sort instead of using sorted()?
+Almost never in production code. Write your own to learn, to answer interview questions, or when you need something unusual, such as a sort that reports progress. For everything else the built-in is faster and well tested.
What does it mean for a sort to be stable?
+Equal elements keep the relative order they had before sorting. It matters when you sort records by one field after another, for example by city and then by name.
Can I binary search a list of strings or tuples?
+Yes, as long as the list is sorted using the same ordering that the comparison uses. bisect works for anything that supports <, and with key= you can search records by a single field.
Is it faster to sort once and binary search, or to just use a set?
+For repeated membership tests, a set is O(1) on average and usually the better choice. Sorted lists win when you need ordering, range queries, the nearest value or the position of a value. See the Big-O lesson for how to weigh these trade-offs.
Key takeaways
- βBubble, selection and insertion sort are O(n squared); insertion sort is the practical one, especially on nearly sorted data.
- βMerge sort guarantees O(n log n) and is stable, at the cost of extra memory; quicksort is usually fast but needs a sensible pivot.
- βUse
sorted()orlist.sort()in real code, withkey=for custom ordering; remember thatlist.sort()returnsNone. - βPython's sort is stable, so you can sort by several fields with repeated passes or one tuple key.
- βBinary search needs sorted data, runs in O(log n), and is safest with a single consistent bounds convention.
- β
bisect_left,bisect_rightandinsortgive you binary search and ordered insertion straight from the standard library.