← Return to Index
|
Complexity |
Note |
Worst Case: |
O(n) |
Occurs when the item isn't in the list |
Best Case: |
O(1) |
If the list is already sorted |
- Check every item in the list
- For every item, check if it is equal to the query
- If the query is found, return True (or the index of the item)
- If the list is sorted, and the current item is greater than the query, return False
- If the entire list has been iterated over, return False
def linear_search(L, query):
for item in L:
if item == query:
return True
# only for sorted lists:
if item > query:
return False
return False
|
Complexity |
Note |
Worst Case: |
O(logn) |
Occurs when the item isn't in the list |
Best Case: |
O(1) |
If the middle item is the query |
- The list is already sorted
- The list allows random access
- Look at the middle of the list
- If the middle item equals the query, return True (or the index)
- If the query is less than the middle item, ignore all items after the middle item
- Otherwise, if the query is greater the the middle item, ignore all items before the middle item
- You now have a sub-list, goto 1 and repeat until item is found.
- If not found, return False (or -1).
def binary_search(L, query):
lower = 0
upper = len(L) - 1
while lower <= upper:
mid = (lower + upper) // 2
if L[mid] == query:
return mid
elif L[mid] < query:
upper = mid - 1
else:
lower = mid + 1
return -1
A class method for lists to search for an item in the list, then return its index.
- Use one of the search methods above
- If not found, throw an exception
- If there are multiple copies and the list is sorted, iterate over entire list until the first appearance of the query is found
- Return the index of this initial appearance
def index(L, query):
position = binary_search(L, query)
if position == -1:
raise Exception("Item not in list!")
# check for multiple copies (only for sorted lists)
while position >= 0 and L[position] == query:
position -= 1
position += 1
return position