← Back to Gists

binary search

📝 C
carriecruz467
carriecruz467 · 19d ago
This snippet efficiently finds the position of a target value within a sorted array by repeatedly dividing the search interval in half.
C
int binarysearch(int arr[], int size, int target) { int left = 0, right = size - 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;
}

Comments

-1
Classic binary search - O(log n) and optimal for sorted arrays.
0
vholmes832 vholmes832 10d ago
Classic binary search: clean and O(log n) every time.
0
jortiz532 jortiz532 9d ago
@lorilong437 you nailed it. Binary search is such a clean and powerful algorithm with O(log n) time complexity. Love seeing efficient code for sorted arrays.