# Function to perform binary search on a sorted array
def binary_search(arr, target):
low, high = 0, 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
# Usage: Perform binary search on a sorted array
arr = [1, 2, 3, 4, 5, 6, 7, 8, 9]
target = 5
result = binary_search(arr, target)Binary Search in Python
python
Related Posts
More content you might like
Tutorial
javascript
JavaScript DSA (Data Structures and Algorithms) Tutorial: A Beginner's Guide
Sorting algorithms arrange the elements of a data structure in a specific order. A common example is the bubble sort algorithm.
Bubble Sort Implementation:
Aug 30, 2024
Read More Code
javascript
Prime Number Check and Prime Number Generation in JavaScript
No preview available for this content.
Jan 26, 2024
Read More Code
java
Swap Two Numbers Without Using a Temporary Variable
No preview available for this content.
Jan 26, 2024
Read MoreDiscussion 0
Please sign in to join the discussion.
No comments yet. Be the first to share your thoughts!