Binary Search is an efficient searching algorithm that works on sorted arrays or lists. It divides the search interval in half repeatedly. If the target value is less than the middle element, the search continues in the left half, or if it is greater, it continues in the right half, narrowing the search until the value is found or the interval is empty.
function binarySearch(arr, target): left = 0 right = length of arr - 1 while left <= right: mid = (left + right) / 2 if arr[mid] == target: return mid else if arr[mid] < target: left = mid + 1 else: right = mid - 1 return -1
#include <stdio.h> int binarySearch(int arr[], int n, int target) { int left = 0, right = n - 1; while (left <= right) { int mid = left + (right - left) / 2; if (arr[mid] == target) { return mid; // Element found, return index } else if (arr[mid] < target) { left = mid + 1; // Search in the right half } else { right = mid - 1; // Search in the left half } } return -1; // Element not found } int main() { int arr[] = {2, 5, 7, 9, 11, 15}; int n = 6; int target = 9; int result = binarySearch(arr, n, target); if (result != -1) printf("Element found at index %d\n", result); else printf("Element not found\n"); return 0; }
The time complexity of Binary Search is O(log n), where 'n' is the number of elements in the array. This is much faster than Linear Search (O(n)) for large datasets, as it reduces the search range by half with each step.
Help others discover Technorank Learning by sharing your honest experience.
Your support inspires us to keep building!