Searching Algorithms Flashcards
1
Q
Basic Algorithm for Binary Search
A
If value == middle -> value found
If value < middle -> end = mid - 1
if value > middle -> start = mid + 1
2
Q
Setup condition for a binary search (inc while loop)
A
low = 0
high = len(array)-1
low <= high
If low goes above high, then the value is not found
Typically you will return low or ValueError
3
Q
Best & Worst Case of Binary Search
A
Best Case: loop stops immediately, item is in the middle of the loop, so it’s just O(m), where m is cost of comp
Worst Case: item is at start/end, therefore complexity is O(log n * m)
This is because each iteration of the loop halves the working space, which is log n