Master the #Basics: Binary Search Algorithm in Python - An #Easy to Follow Explanation

preview_player
Показать описание
#Binary #search is a more efficient search #algorithm compared to #linear #search, especially when searching a large #list or #array. It works by dividing the list into half repeatedly and checking if the target element is present in the left or right half until the target element is found or it is determined that the element is not in the list. The #time #complexity of binary search is O(log n) in the worst case scenario, where n is the number of elements in the list or array.

Here's an #implementation of binary search in #Python:

def binary_search(arr, target):
low = 0
high = len(arr) - 1
while low <= high:
mid = (low + high) // 2
if arr[mid] == target:
return mid
elif arr[mid] < target:
low = mid + 1
else:
high = mid - 1
return -1
This implementation takes a sorted list "arr" and a target element "target" as inputs and returns the index of the target element if it is found in the list, or -1 if the target element is not in the list. It is important to note that binary search can only be used on sorted lists or arrays.
Рекомендации по теме
Комментарии
Автор

thank you for posting this at the perfect time!

cbduffy
Автор

Is binary search working on unsorted Array?

djkoko