| FazBrowse GitHub Viewer | Trending | | Home |
| Tools: [Download Repo ZIP] [Original HTTPS Page] |
| Name | Name | Last commit date | ||
|---|---|---|---|---|
Our Python Code Repository is a community-driven platform for sharing high-quality Python programs. With contributions from members of the community, our repository contains a collection of Python codes for others to learn from and use. We welcome contributions from anyone who wants to share their code and follow our guidelines. Our moderators review all pull requests to ensure the quality and consistency of our repository. Join our community and contribute to creating a valuable resource for Python developers worldwide.
def binary_search(target, lst):
"""
Performs binary search on a sorted list to find the index of a target element.
Args:
target (int): The target element to find in the list.
lst (list): The sorted list to search in.
Returns:
int: The index of the target element in the list, or -1 if it is not found.
"""
count_iterations = 0 # Counter for the number of iterations required to perform the search
start_index = 0 # The starting index of the search range
end_index = len(lst) - 1 # The ending index of the search range
# Perform binary search until the target element is found or the search range is exhausted
while start_index <= end_index:
count_iterations += 1
mid_index = (start_index + end_index) // 2 # Calculate the midpoint index of the search range
if target < lst[mid_index]:
end_index = mid_index - 1 # Adjust the search range to the lower half
elif target > lst[mid_index]:
start_index = mid_index + 1 # Adjust the search range to the upper half
else:
return mid_index # The target element is found at the midpoint index
return -1 # The target element is not found in the listmid_index=start+(end-start)//2Commit message for the same would be:
Mid integer overflowing avoided
Extended (optional) description could be:
In the formula mid = (start + end) / 2, if start and end are large integers, adding them may exceed the maximum value that can be stored in an integer variable, leading to integer overflow and potentially incorrect results.
| Back | FazBrowse Home | New Git URL |