In Class: Week 8
Search
Topics
- Searching using the in and not in operators
- Linear search
- Complexity of linear search
- Big-O notation
- Binary search
- Complexity of binary search
In-class work
Linear Search
- We have used Python functions for searching (e.g., in, list.find()). How
do these methods actually work? We will discuss the algorithm for searching
a collection of items.
- Open up the file searchCards.py. This program creates a list
of random ints and asks the user for a value to search the list for. We will
write a function findCard() that takes in a deck of cards (a list of
ints) and an int value to search for. Our function can return a boolean
value for whether the value was found, or the actual position of the value
in the list.
Complexity of Search
- How do we analyze how long it takes for search to finish? We will count
steps to analyze a programs complexity. What counts as a step? What
happens in the best case? Worst case? How many steps does linear search
take in the worst case?
Binary Search
- Using playing cards, we will consider how we can make searching go faster
if the list of items is in sorted order. Binary search works by using divide
and conquer. Each step of the algorithm divides the number of items to search
in half until it finds the value or has no items left to search.
- In testsearches.py, we will implement the binary search algorithm
to search a list for some random value.
- Why is it called binary search? How many steps does it take for binary
search to run? We will see that binary search is O(log N). What does this
mean relative to linear search? Run testsearches.py with different
values of N to see how the run time of binary search grows with increasing
list sizes. How does this compare to linear search's growth?
include("style/footer.php"); ?>