# 619480
import time
from random import *
def main():
lst = []
result, length = 0, 500000
while result <= 0.50:
for i in range(length):
lst.append(randint(1, length))
value = randint(1, length)
t0 = time.clock()
linearSearch(value, lst)
result = time.clock() - t0
print("This LINEAR SEARCH took {0:4.2f}seconds with a length of".format(result), length)
lst.sort()
t0 = time.clock()
binarySearch(value, lst)
result = time.clock() - t0
print("This BINARY SEARCH took {0:4.2f}seconds with a length of".format(result), length, "\n")
lst = []
length = length + 500000
def binarySearch(value, lst):
low, high = 0, len(lst) - 1
while low <= high:
mid = (low + high) // 2
item = lst[mid]
if value == item:
return mid
elif value < item:
high = mid - 1
else:
low = mid + 1
return -1
def linearSearch(value, lst):
for i in range(len(lst)):
if value == lst[i]:
return i
return -1
main()
I'm trying to time the two algorithms at the bottom using the clock function. The linearSearch get's timed fine, it gives me a value, however, when it comes to timing the binarySearch, it always reports 0.00. Why? What am I doing wrong? :s