algo5
algo5
Lecture 5
Cyrille Rosset
Université Paris Cité
11 November 2022
1 Searching algorithms
Sequential search
Binary search
Binary tree search
1 Searching algorithms
Sequential search
Binary search
Binary tree search
1 Searching algorithms
Sequential search
Binary search
Binary tree search
Informal description
In the sequential search, we search for an item by iterating over each data element
and comparing to to the searched item.
Code
def sequential_search(x, array):
for i, item in enumerate(array):
if x == item:
return i # if we find it, we return its index
return None
Complexity
Space: O(1)
Time: it depends where is the searched element. We distinguish best case (1),
average case (N/2) and worst case (N).
1 Searching algorithms
Sequential search
Binary search
Binary tree search
Informal description
When searching a word in the dictionary, you will usualli no go through each page,
but rather look directly in the middle, then check if the word you’re looking for is
before an after, and you will repeat the opration until finding the word.
Binary search is using this technic, dividing each time the search interval by 2.
Note that the input array must be sorted!
Code
def binary_search(x, array):
lo, hi = 0, len(array)-1
while lo <= hi:
i = (lo + hi) // 2
if array[i] == x:
return True
elif array[i] > x:
hi = i - 1
else:
lo = i + 1
return False
Complexity
Average case: O(log N) (not taking into account the sorting).
Worst case: O(log N) as well.
1 Searching algorithms
Sequential search
Binary search
Binary tree search
Description
Very important algorithm, though very simple.
For binary tree search, we build a binary tree where each node contain an element
of data (so we have N nodes), and each node is such that all nodes on its left
branch are smaller and all nodes on its right branch are larger or equal.
A R
C H