# Searching¶

## Search Problem Definition¶

Given a list aList of length n and an item, is item present in aList?

• If item is in aList, return True

• else return False

### Searching in an Unsorted List¶

def linearSearch(aList, item):
n = len(aList)
for el in aList:
if item == el:
return True
return False
linearSearch([12, 16, 23, 2, 7], 16)
True
linearSearch([12, 16, 23, 2, 7], 13)
False
linearSearch(['a', 'e', 'i', 'o', 'u'], 'u')
True
linearSearch(['a', 'e', 'i', 'o', 'u'], 'a')
True
linearSearch(['hello', 'world', 'silly'], 'hi')
False

### Searching in a Sorted List¶

Can we do better if the given list aList is sorted? Yes!

Let’s implement a binary search function below.

def binarySearch(aList, item):
"""Assume aList is sorted. If item is
in aList, return True; else return False."""
n = len(aList)
mid = n // 2
# base case 1
if n == 0:
return False

# base case 2
elif item == aList[mid]:
return True

# recurse on left
elif item < aList[mid]:
return binarySearch(aList[:mid], item)

# recurse on right
else:
return binarySearch(aList[mid + 1:], item)
binarySearch(['a', 'e', 'i', 'o', 'u'], 'a')
True
binarySearch(['a', 'e', 'i', 'o', 'u'], 'b')
False
binarySearch(sorted(['hello', 'world', 'silly']), 'hi')
False
binarySearch(sorted(['hello', 'world', 'silly']), 'hello')
True
numList = [23, 1, 2, 90, 0, 10, 12, 120, 45]
numList.sort()
numList
[0, 1, 2, 10, 12, 23, 45, 90, 120]
binarySearch(numList, 11)
False
binarySearch(numList, 45)
True