Lesson 36 of 50
cSearching Algorithms – Linear & Binary Search
10 mins
Course progress72%
What you'll learn
Keep these ideas in mind as you work through the lesson.
Lesson 36 of 50
c10 mins
Keep these ideas in mind as you work through the lesson.
Search for a target value in a collection.
Implementation tip: Use size_t for indexes, and always check bounds.
int binsearch(const int *a, size_t n, int key) {
size_t lo = 0, hi = n;
while (lo < hi) {
size_t mid = lo + (hi - lo) / 2;
if (a[mid] == key) return (int)mid;
else if (a[mid] < key) lo = mid + 1;
else hi = mid;
}
return -1; // not found
}