Material for Lectures 19 and 20 is in Chapters 10 and 11 of the text.
We’ve already covered this briefly in Lecture 13.
Implement two (or more) algorithms to find the indices of the two smallest values in the list:
import random
import time
def index_two_v1( values ):
pass # don't do anything; using 'pass' prevents syntax errors
def index_two_v2( values ):
pass
if __name__ == "__main__":
n = int(raw_input("Enter the number of values to test ==> "))
values = range(0,n)
random.shuffle( values )
s1 = time.time()
(i0,i1) = index_two_v1(values)
t1 = time.time() - s1
print "Ver 1: indices (%d,%d); time %.3f seconds" %(i0,i1,t1)
s2 = time.time()
(j0,j1) = index_two_v2(values)
t2 = time.time() - s2
print "Ver 2: indices (%d,%d); time %.3f seconds" %(j0,j1,t2)
We will experiment with at least two implementations.
Write a Python function called linear_search that returns the index of the first instance of x in L or determines that it is not there (and returns a -1).
What if the list is already sorted? Write a modifed version of linear_search that returns the index of the first instance of x or the index where x should be inserted if it is not in L For example, in the list
L = [ 1.3, 7.9, 11.2, 15.3, 18.5, 18.9, 19.7 ]
the call
linear_search(11.9, L)
should return 3.
We need to keep track of two indices:
Initialize low = 0 and high = N.
In each iteration of a while loop
Here is the actual code:
def binary_search( x, L):
low = 0
high = len(L)
while low != high:
mid = (low+high)/2
if x > L[mid]:
low = mid+1
else:
high = mid
return low
Using
L = [ 1.3, 7.9, 11.2, 15.3, 18.5, 18.9, 19.7 ]
what are the values of low, high and mid each time through the while loop for the calls
binary_search( 11.2, L )
binary_search( 19.1, L )
binary_search( -1, L)
binary_search( 25, L)
How many times will the loop execute for or ? (You will not be able to come up with an exact number, but you should be able to come close.) How does this compare to the linear search?
Would the code still work if we changed the > to the >=? Why?
Modify the code to return a tuple that includes both the index where x is or should be inserted and a boolean that indicates whether or not x is in the list.
We will also perform experimental timing runs if we have time at the end of class.