Skip to main content
Brave Programmer Logo

BraveProgrammer

BraveProgrammer

HomeProjectsBlogsCoursesLessonsAbout

Site footer

BraveProgrammer

Free coding courses, practical tutorials, and real projects from BraveProgrammer. Learn web development with React, Next.js, and TypeScript.

Navigation

  • Home
  • Projects
  • Blogs
  • Courses

Resources

  • About
  • Lessons

© 2026 BraveProgrammer. All rights reserved.

  1. Courses
  2. /
  3. C Programming Fundamentals

Lesson 36 of 50 · c

Searching Algorithms – Linear & Binary Search

Duration: 10 mins

Search for a target value in a collection.

  • Linear Search – scan each element sequentially – O(n).
  • Binary Search – works on sorted arrays – repeatedly halve the search interval – O(log n).

Implementation tip: Use size_t for indexes, and always check bounds.


📚 Binary Search (Iterative)

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
}
Previous: Sorting Algorithms – QuickSort & MergeSortNext: Bit Manipulation Techniques