Given a sorted list of elements, if an element youβre looking for is in that list, binary search returns the position where itβs located. Otherwise, binary search returns null.
Computational Complexity: log2β N
#include <stdio.h>
int binarySearch(int list[], int high, int number) {
int low = 0;
while (low <= high) {
int middle = (low + high) / 2;
if (list[middle] == number) {
return middle;
}
if (list[middle] < number) {
low = middle + 1;
} else {
high = middle - 1;
}
}
return -1;
}
## binarySearch({1, 5, 3, 2}, 3, 2) => position 3
## binarySearch({1, 5, 3, 2}, 3, 8) => -1