# 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
Example:
let numbers = [10, 20, 30, 40, 50];
// Accessing elements
console.log(numbers[0]); // Output: 10
// Modifying elements
numbers[1] = 25;
console.log(numbers[1]); // Output: 25
// Adding elements
numbers.push(60);
console.log(numbers); // Output: [10, 25, 30, 40, 50, 60]
// Removing elements
numbers.pop();
console.log(numbers); // Output: [10, 25, 30, 40, 50]Aug 30, 2024
Read More Code
javascript
Prime Number Check and Prime Number Generation in JavaScript
// Function to check if a number is prime
function isPrime(num) {
if (num <= 1) return false;
if (num <= 3) return true;
if (num % 2 === 0 || num % 3 === 0) return false;
for (let i = 5; i * i <= num; i += 6) {
if (num % i === 0 || num % (i + 2) === 0) return false;
}
return true;
}
// Usage: Generate prime numbers between 2 and 100
let primes = [];
for (let i = 2; i <= 100; i++) {
if (isPrime(i)) {
primes.push(i);
}
}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!