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
  • Teach on BraveProgrammer

© 2026 BraveProgrammer. All rights reserved.

Searching Algorithms – L | C Programming Fundamentals lesson | BraveProgrammer
  1. Courses
  2. /
  3. C Programming Fundamentals

Lesson 36 of 50

·c

Searching Algorithms – Linear & Binary Search

10 mins

Course progress72%

What you'll learn

Keep these ideas in mind as you work through the lesson.

4 points
  • Linear search is simple and works on unsorted data.
  • Binary search requires sorted input; otherwise result is undefined.
  • Iterative binary search avoids recursion overhead.
  • Use `size_t` for array indices to avoid negative values.

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
}
Make it stickPractice what you've learned1 quiz · 3 practical tests · Optional activities from C Programming FundamentalsBrowse activities
Previous lessonSorting Algorithms – QuickSort & MergeSortContinue to lesson 37Bit Manipulation TechniquesBack to C Programming Fundamentals curriculum