Here are some examples of binary search algorithms in different scenarios:
### 1. **Basic Binary Search (Iterative Approach)**
This algorithm searches for a target value in a sorted array.
**Code Example (Python):**
```python
def binary_search(arr, target):
left, right = 0, len(arr) - 1
while left <= right:
mid = left + (right - left) // 2
if arr[mid] == target:
return mid
elif arr[mid] < target:
left = mid + 1
else:
right = mid - 1
return -1 # Element not found
# Usage
array = [1, 3, 5, 7, 9, 11]
print(binary_search(array, 5)) # Output: 2
```
### 2. **Binary Search (Recursive Approach)**
The same binary search implemented recursively.
**Code Example (Python):**
```python
def binary_search_recursive(arr, target, left, right):
if left > right:
return -1 # Element not found
mid = left + (right - left) // 2
if arr[mid] == target:
return mid
elif arr[mid] < target:
return binary_search_recursive(arr, target, mid + 1, right)
else:
return binary_search_recursive(arr, target, left, mid - 1)
# Usage
array = [1, 3, 5, 7, 9, 11]
print(binary_search_recursive(array, 7, 0, len(array) - 1)) # Output: 3
```
### 3. **Binary Search for First Occurrence**
Find the first occurrence of a target value in a sorted array with duplicates.
**Code Example (Python):**
```python
def binary_search_first_occurrence(arr, target):
left, right = 0, len(arr) - 1
result = -1
while left <= right:
mid = left + (right - left) // 2
if arr[mid] == target:
result = mid
right = mid - 1 # Search in the left half for first occurrence
elif arr[mid] < target:
left = mid + 1
else:
right = mid - 1
return result
# Usage
array = [2, 4, 10, 10, 10, 18, 20]
print(binary_search_first_occurrence(array, 10)) # Output: 2
```
### 4. **Binary Search for Square Root (Integer Part)**
Find the integer part of the square root of a number.
**Code Example (Python):**
```python
def binary_search_sqrt(n):
if n < 2:
return n
left, right = 1, n // 2
while left <= right:
mid = left + (right - left) // 2
if mid * mid == n:
return mid
elif mid * mid < n:
left = mid + 1
result = mid
else:
right = mid - 1
return result
# Usage
print(binary_search_sqrt(10)) # Output: 3
```
### 5. **Binary Search on a 2D Matrix**
Given a matrix where each row is sorted, perform a binary search.
**Code Example (Python):**
```python
def binary_search_matrix(matrix, target):
if not matrix or not matrix[0]:
return False
rows, cols = len(matrix), len(matrix[0])
left, right = 0, rows * cols - 1
while left <= right:
mid = left + (right - left) // 2
mid_value = matrix[mid // cols][mid % cols]
if mid_value == target:
return True
elif mid_value < target:
left = mid + 1
else:
right = mid - 1
return False
# Usage
matrix = [
[1, 3, 5],
[7, 9, 11],
[13, 15, 17]
print(binary_search_matrix(matrix, 9)) # Output: True
```
These examples demonstrate how binary search can be applied to different data structures and problem
types.