Agenda:
an explicit, precise, unambiguous, mechanically-executable sequence of elementary instructions, usually intended to accomplish a specific purpose.
Examples?
Lagniappe: Another old algorithmic drinking song is The Barley Mow. I'll leave it to you to come up with the program to produce it.
Examples of algorithm-like things that are not algorithms?
What if it took Google took 2 minutes to return results?¶
Simple warmup: What does this do?
def my_function(a, b):
for i,v in enumerate(a):
if v == b:
return i
return -1
def linear_search(mylist, key):
"""
Args:
mylist...a list
key......a search key
Returns:
index of key in mylist; -1 if not present
"""
for i,v in enumerate(mylist):
if v == key:
return i
return -1
linear_search([5,1,10,7,12,4,2], 12)
4
What factors affect the running time of this algorithm?
$ \hbox{Cost(linear-search, mylist, key)} = \sum_i c_i * n_i $
def linear_search(mylist, key): # cost number of times run
for i,v in enumerate(mylist): # c1 ?
if v == key: # c2 ?
return i # c3 ?
return -1 # c4 ?
To deal with the effects of the input values on performance, we can consider three types of analysis:
linear_search([5,1,10,7,12,4,2], 9999)
linear_search([5,1,10,7,12,4,2], 5)
for (mylist, key) in ???:
linear_search(mylist, key)
Assume $n \leftarrow$ len(mylist)
def linear_search(mylist, key): # cost number of times run
for i,v in enumerate(mylist): # c1 n
if v == key: # c2 n
return i # c3 0
return -1 # c4 1
$ \hbox{Cost(linear-search, } n) = c_1n + c_2n + c_4$
Cost is now just a function of:
Consider this slightly different implementation:
def new_linear_search(mylist, key): # cost number of times run
for i in range(len(mylist)): # c5 n
if mylist[i] == key: # c6 n
return i # c3 0
return -1 # c4 1
$ \begin{align} \hbox{Cost(new-linear-search, } n) = c_5n + c_6n + c_4\\ \hbox{Cost(linear-search, } n) = c_1n + c_2n + c_4 \end{align} $
There is a line between analyzing algorithms and optimizing a specific implementation (e.g., through profiling):

$ c_1n + c_2n + c_4 \approx c_5n + c_6n + c_4 $
Mathematically define our Asymptotic Notations and introduce tools for performing asymptotic proofs.