Skip to content

Commit 739d170

Browse files
committed
simplifiying the binary search
1 parent ae68a78 commit 739d170

File tree

1 file changed

+26
-0
lines changed

1 file changed

+26
-0
lines changed

searches/binary_search.py

Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -321,6 +321,28 @@ def exponential_search(sorted_collection: list[int], item: int) -> int:
321321
return -1
322322
return last_result
323323

324+
#binary search uses divide and conquer
325+
#We will leverage the fact that our list is sorted
326+
def binary_search2(l,target, low=None,high=None):
327+
if low is None:
328+
low=0
329+
if high is None:
330+
high=len(l)-1
331+
if high < low:
332+
return -1
333+
334+
midpoint=(low+high) // 2
335+
if l[midpoint] == target:
336+
return midpoint
337+
elif target <l [midpoint]:
338+
return binary_search(l,target,low,midpoint-1)
339+
else:
340+
return binary_search(l,target,midpoint+1,high)
341+
342+
343+
344+
345+
324346

325347
searches = ( # Fastest to slowest...
326348
binary_search_std_lib,
@@ -358,3 +380,7 @@ def exponential_search(sorted_collection: list[int], item: int) -> int:
358380
print(f"{target} was not found in {collection}.")
359381
else:
360382
print(f"{target} was found at position {result} of {collection}.")
383+
384+
#Testing the binary search 2
385+
mylist=[1,2,3,4,5,6,7,8,9,10]
386+
print(binary_search(mylist,10) )

0 commit comments

Comments
 (0)