Given a list L
of length n
and an item e
, is item e
present in L
?
L
, return its location (index) in L
; -1
indicating its not in L
.Let's start with a unsorted list first and revisit our linearSearch algorithm.
def linearSearch(L, e):
n = len(L)
for item in L:
if item == e:
return True
return False
linearSearch([12, 16, 23, 2, 7], 16)
linearSearch([12, 16, 23, 2, 7], 13)
linearSearch(['a', 'e', 'i', 'o', 'u'], 'u')
linearSearch(['a', 'e', 'i', 'o', 'u'], 'a')
linearSearch(['hello', 'world', 'silly'], 'hi')
Can we do better if the given list L
is sorted?
Let's implement binary search below.
def binarySearch(L, e):
"""Assume L is sorted.
If e in L, return True;
else return False."""
n = len(L)
if n == 0:
return False
else:
m = n//2
if e == L[m]:
return True
elif e < L[m]:
return binarySearch(L[:m], e)
else:
return binarySearch(L[m+1:], e)
binarySearch(['a', 'e', 'i', 'o', 'u'], 'a')
binarySearch(['a', 'e', 'i', 'o', 'u'], 'b')
binarySearch(sorted(['hello', 'world', 'silly']), 'hi')
binarySearch(sorted(['hello', 'world', 'silly']), 'hello')
numList = sorted([23, 1, 2, 90, 0, 10, 12, 120, 45])
binarySearch(numList, 11)
binarySearch(numList,0)
binarySearch(numList, 45)
def selectionSort(L):
"""Destructive sort of list L,
returns sorted list."""
n = len(L)
for i in range(n):
minPosition = i
for j in range(i+1, n):
if L[minPosition] > L[j]:
minPosition = j
L[i], L[minPosition] = L[minPosition], L[i]
return L
selectionSort([1, 43, 22, 99, 100])
list('shikha')
selectionSort(list('shikha'))
selectionSort(list('We hate Covid-19'))