Skip to content

Instantly share code, notes, and snippets.

@equalent
Created August 17, 2019 15:03
Show Gist options
  • Select an option

  • Save equalent/35e995c2b463987126a82af422b3beac to your computer and use it in GitHub Desktop.

Select an option

Save equalent/35e995c2b463987126a82af422b3beac to your computer and use it in GitHub Desktop.
Simple search vs binary search vs CPython list index
from typing import List
from random import randint
import timeit
def simple_search(haystack: List[int], needle: int):
for idx, i in enumerate(haystack):
if i == needle:
return idx
def binary_search(haystack: List[int], needle: int):
low = 0
high = len(haystack) - 1
while True:
mid = (low + high) // 2
guess = haystack[mid]
if guess < needle:
low = mid + 1
elif guess > needle:
high = mid - 1
else:
return mid
arr = []
for i in range(50):
arr.append(randint(0, 34562465))
arr.append(5999999999)
arr.sort()
def test0():
simple_search(arr, 5999999999)
def test1():
binary_search(arr, 5999999999)
def test2():
arr.index(5999999999)
print(timeit.timeit("test0()", setup="from __main__ import test0"))
print(timeit.timeit("test1()", setup="from __main__ import test1"))
print(timeit.timeit("test2()", setup="from __main__ import test2"))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment