Junior — Middle
Explain the working mechanism of the binary search algorithm and how it is performed in practice.
sobes.tech AI
Answer from AI
Binary search is an algorithm for finding an element in a sorted array that operates in logarithmic time O(log n).
How it works:
- Determine the middle of the array.
- Compare the target value with the middle element.
- If they match, return the index.
- If the target is less, search in the left half of the array.
- If greater, search in the right half.
- Repeat the process recursively or iteratively until the element is found or there are no more elements to search.
Example in Java:
public int binarySearch(int[] arr, int target) {
int left = 0;
int right = arr.length - 1;
while (left <= right) {
int mid = left + (right - left) / 2;
if (arr[mid] == target) {
return mid;
} else if (arr[mid] < target) {
left = mid + 1;
} else {
right = mid - 1;
}
}
return -1; // element not found
}
It is important that the array is sorted; otherwise, the algorithm does not guarantee correct results.