Sub topic 5
Traversing and Searching an Array
This chapter assumes you can write loops and functions and know introductory Big-O notation. It also assumes you know that array elements sit side by side in memory, so any index can be reached in O(1) time.
Traversal
Traversal means visiting every element once. An array of n elements takes O(n) time to traverse, because each visit costs O(1). The extra memory is O(1), because you only need a counter and perhaps an accumulator.
def total(values):
result = 0
for i in range(len(values)):
result += values[i]
return result
print(total([4, 8, 15]))This prints 27. Traversal is the base for most array work, including sums, maximums, counting, and copying. Copying is how a resize moves elements to a new block.
Linear search
Linear search checks elements from the front until it finds the target or runs out of elements. It returns the index, or -1 if the target is absent.
def linear_search(values, target):
for i in range(len(values)):
if values[i] == target:
return i
return -1The cost depends on where the target is:
| Case | Where the target is | Comparisons |
|---|---|---|
| Best | First element | 1 |
| Average | Anywhere, equally likely | About n/2 |
| Worst | Last element or missing | n |
So linear search is O(n). It works on any array, sorted or not.
Binary search
If the array is sorted, you can do better. Compare the target with the middle element, then discard the half that cannot contain it. Random access makes the jump to the middle O(1). Each step halves the range, so the search takes O(log n) comparisons.
def binary_search(values, target):
low, high = 0, len(values) - 1
while low <= high:
mid = (low + high) // 2
if values[mid] == target:
return mid
elif values[mid] < target:
low = mid + 1
else:
high = mid - 1
return -1
data = [3, 8, 15, 21, 42]
print(linear_search(data, 21))
print(binary_search(data, 42))
print(binary_search(data, 5))This prints 3, 4, and -1.
Binary search needs both a sorted array and O(1) indexing. A structure without fast indexing, such as a linked list, loses the advantage.
Common errors
- Off-by-one loop bounds.
range(len(values) + 1)reads one slot past the end and raisesIndexError. Valid indexes run from 0 tolen(values) - 1. - Searching an unsorted array with binary search. The function runs without error but can return
-1for a value that is present. - Wrong loop condition in binary search. Using
low < highskips the case where one element remains. - Adding or removing elements during a loop. Shifting moves elements under your index, so you can skip or repeat items.
Choosing a search
Sorting first costs O(n log n). That pays off only when you search the same data many times. For a single lookup on unsorted data, one linear pass at O(n) is cheaper than sorting. For repeated lookups by key, a different structure, such as a hash table, may fit better.
Exercise
An unsorted array holds 1,000,000 numbers and you need to check one value once. Is it cheaper to sort and then use binary search, or to use linear search? Why?
Show answer
Linear search is cheaper. It takes at most about 1,000,000 comparisons. Sorting costs O(n log n), roughly 20 million steps, before binary search even starts. Sorting only pays off if you run many searches on the same data.