Source code for search

"""This module shows two methods for search to find an index and 
a third one is shown for comparison of computational complexity.

* Method 1: linear search, O(N) complexity
* Method 2: binary search, O(log N) complexity
* Method 3: set solution (for membership check only), O(1) complexity

We can see the difference in running times by executing this module.

"""

import random
import time




if __name__=="__main__":
    #Testing three ways to search a long list. Calling with 100 
    #test values.

    N = 100000
    l = []
    for i in range(N):
        l.append(random.randint(1,N*100))
        
    l.sort()
    lset = set(l)
    
    testN = 100
    testvals = []
    for i in range(testN):
        testvals.append(random.randint(1,N))

    ##Linear search is O(N), which is costly. But this is the most 
    ##general algorithm. It works for lists, returns an index and
    ##works when the list is not sorted.
    test_search( lin_search, l, testvals)
 
    ##Binary search is O(log N), but only works when the input list
    ##is sorted.
    test_search( bin_search, l, testvals)

    #Note the set solution is O(1), or constant time, the fastest of all
    ##three. But it is not equivalent to the above two functions as
    ##it does not give an index.
    test_search( set.__contains__, lset, testvals)