Binary Search Implementation
#include <stdio.h> // Helper function to perform binary search int binarySearch(int arr[], int low, int high, int target) { // Loop continues as long as the search space is valid while (low <= high) { // Calculate the middle index to avoid potential overflow int mid = low + (high...
This C code implements the binary search algorithm, a highly efficient method for finding an element within a sorted array. It works by repeatedly dividing the search interval in half. If the value of the search key is l...
The `binarySearch` function takes a sorted integer array, the lower and upper bounds of the search interval (`low` and `high`), and the `target` value to find. The `while (low <= high)` loop ensures the search continues as long as there's a valid interval. The `mid` index is calculated carefully as `low + (high - low) / 2` to prevent integer overflow that could occur with `(low + high) / 2` if `low` and `high` are very large. If `arr[mid]` matches the `target`, its index is returned. If `arr[mid]` is less than `target`, the search continues in the right half by setting `low = mid + 1`. Otherwise, it searches the left half by setting `high = mid - 1`. If the loop finishes without finding the target, -1 is returned. The time complexity is O(log n) because the search space is halved in each step. The space complexity is O(1) as it uses a constant amount of extra space. Edge cases include an empty array (where `high` will be -1 initially, making `low <= high` false), and the target being smaller than the smallest element or larger than the largest element.
function binarySearch(array, low, high, target): while low <= high: mid = low + (high - low) / 2 if array[mid] == target: return mid else if array[mid] < target: low = mid + 1 else: high = mid - 1 return -1 // Target not...