Linear search
The simplest way to find something is to check every item in turn:
def linear_search(items, target):
for i, item in enumerate(items):
if item == target:
return i
return -1
print(linear_search([4, 8, 15, 16, 23, 42], 23)) # 4
For a list of n items it may need n checks. A list of a million items can take a million steps.
Binary search
If the list is sorted, you can do much better. Look at the middle item: if the target is smaller, throw away the right half, otherwise the left half. Repeat.
def binary_search(items, target):
low, high = 0, len(items) - 1
while low <= high:
mid = (low + high) // 2
if items[mid] == target:
return mid
if items[mid] < target:
low = mid + 1
else:
high = mid - 1
return -1
print(binary_search([4, 8, 15, 16, 23, 42], 23)) # 4
Each step halves the search, so a million sorted items need at most about 20 checks. This is the same idea you use to find a word in a printed dictionary.
Bubble sort
Bubble sort repeatedly swaps neighbours that are in the wrong order, so the largest values "bubble" to the end:
def bubble_sort(items):
items = items[:] # work on a copy
for end in range(len(items) - 1, 0, -1):
swapped = False
for i in range(end):
if items[i] > items[i + 1]:
items[i], items[i + 1] = items[i + 1], items[i]
swapped = True
if not swapped:
break # already sorted
return items
print(bubble_sort([5, 1, 4, 2, 8])) # [1, 2, 4, 5, 8]
It is easy to understand but slow on big lists: roughly n² comparisons.
Comparing speed with Big O
Programmers describe how work grows with input size using Big O notation:
- O(n), linear search: twice the data, twice the work.
- O(log n), binary search: twice the data, just one more step.
- O(n²), bubble sort: twice the data, four times the work.
- O(n log n): the best general sorting algorithms, such as merge sort. Python's built-in
sorted()uses an algorithm in this class.
In real programs, use the built-in sorted() or list.sort(). Writing your own sort is for learning how they work.
Try it yourself
In Unays Code, add a counter to linear_search and binary_search to count comparisons, then search a sorted list of 100,000 numbers with each. Compare the counts.
This tutorial was written with AI assistance and reviewed by Unays. The runnable code examples were tested before publishing. Spotted a mistake? Tell us at [email protected].