# 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
Related Posts
More content you might like
JavaScript DSA (Data Structures and Algorithms) Tutorial: A Beginner's Guide
Data Structures and Algorithms (DSA) are fundamental concepts in computer science and software development. Understanding these concepts is crucial for writing efficient code and solving complex problems. This tutorial will introduce you to the basics of DSA using JavaScript, covering essential data structures and algorithms, and how they can be implemented in JavaScript.
Data structures are ways to organize and store data so that it can be accessed and modified efficiently. The choice of data structure can greatly affect the performance of your application, making it essential to understand when and how to use them.
Prime Number Check and Prime Number Generation in JavaScript
No preview available for this content.
Swap Two Numbers Without Using a Temporary Variable
int a = 5, b = 10;
a = a + b;
b = a - b;
a = a - b;
System.out.println("a = " + a + ", b = " + b);Discussion 0
Please sign in to join the discussion.
No comments yet. Be the first to share your thoughts!