TalentJR

⚙️ C programming basics · Class 10 · Lesson 16 of 18 · Free

Searching Algorithms in C – Linear Search and Binary Search

⏱ About 35 minutes · ▶ run real C here — nothing to install · no sign-in

In this lesson you will

  • Write linear search and say when it is the right choice
  • Write binary search with low, mid and high, and trace its steps
  • Compare the number of steps and use the library function bsearch

Looking up a word in a dictionary, you never start at page 1. You open the middle, see if your word comes before or after, and throw away half the book. Doing that again and again finds any word in a few steps. That trick is binary search, and in this lesson you compare it with the simple page-by-page way.

What is linear search in C?

Linear search checks each item from the start until it finds the target or reaches the end. It returns the index where it found the item, or -1 for "not found".

It works on ANY array, sorted or not. That is its big strength.

Its weakness: in the worst case it looks at every item. Try it: search for 42, which is not in the list, and see the number of checks.

⚙️ C — you can edit this code
Output
Roll 31 found at index 4
Checks made: 5

How does binary search work in C?

Binary search only works on a SORTED array. It keeps a range from low to high and looks at the middle item, mid.

If the middle item is the target, done. If the target is bigger, it can only be in the right half, so low = mid + 1. If smaller, high = mid - 1. When low passes high, the range is empty: not found.

This program prints every step. Try it: search for 70, then for 5, and watch the range shrink.

⚙️ C — you can edit this code
Output
Step 1: low=0 high=9 mid=4 (value 58)
Step 2: low=5 high=9 mid=7 (value 84)
84 found at index 7

💡 low + (high - low) / 2 is the same as (low + high) / 2, but cannot overflow for huge arrays.

Linear search vs binary search: which is faster?

Binary search halves the range every step. A million items can be halved only about 20 times before one is left. So it needs at most about 20 checks, while linear search may need a million.

We say linear search is O(n) and binary search is O(log n). This program counts the checks for the last item in bigger and bigger sorted arrays.

But remember: binary search needs sorted data. Sorting costs time too (Lesson 15), so it pays off when you search the same data many times.

⚙️ C — you can edit this code
Output
n =    1000: linear    1000 checks, binary 10 checks
n =  100000: linear  100000 checks, binary 17 checks
n = 1000000: linear 1000000 checks, binary 20 checks

How do you write binary search with recursion in C?

Binary search fits recursion (Lesson 11) well. Each call searches a smaller half, and the base case is an empty range.

Here the data is sorted names, compared with strcmp (Lesson 3). strcmp returns less than 0, 0 or more than 0, just like a number comparison.

Try it: search for "Zara" and see that the empty range ends the recursion.

⚙️ C — you can edit this code
Output
Ramayana is on shelf 5

How do you use bsearch in C?

Like qsort (Lesson 15), the C library has `bsearch` in <stdlib.h>. You give it a pointer to the key, the sorted array, the count, the item size and a compare function.

It returns a pointer to the found item, or NULL if there is none. The compare function must order items the same way the array was sorted.

Here we look up a bus pass by its pass number. Try it: look up 2045, which is missing.

⚙️ C — you can edit this code
Output
Pass 2010 belongs to Meena

💡 (x > y) - (x < y) gives 1, 0 or -1 and never overflows.

🤔 Predict the output

Think like C: read the code and choose what it prints. You get the reason straight away.

Question 1. 7 appears twice. What does this linear search print?

int a[] = { 4, 7, 9, 7 };
int pos = -1;
for (int i = 0; i < 4; i++) {
    if (a[i] == 7) { pos = i; break; }
}
printf("%d\n", pos);

Question 2. How many steps does binary search need to find 23?

int a[] = { 2, 5, 8, 12, 16, 23, 38, 56, 72, 91 };
int low = 0, high = 9, steps = 0;
while (low <= high) {
    int mid = low + (high - low) / 2;
    steps++;
    if (a[mid] == 23) break;
    if (a[mid] < 23) low = mid + 1; else high = mid - 1;
}
printf("%d\n", steps);

Question 3. Binary search on an UNSORTED array, looking for 9. What does it print?

int a[] = { 9, 2, 7, 4, 5 };
int low = 0, high = 4, pos = -1;
while (low <= high) {
    int mid = low + (high - low) / 2;
    if (a[mid] == 9) { pos = mid; break; }
    if (a[mid] < 9) low = mid + 1; else high = mid - 1;
}
printf("%d\n", pos);

🧩 Your challenge

A railway enquiry counter has train numbers sorted from low to high. Read train numbers until 0 is typed. For each one, use binary search to print the train's name and how many steps it took, or say it was not found. Example for inputs 12951, 11111, 0: 12951: Coastal Express (found in 2 steps) 11111: no such train (3 steps)

Expected output (with the inputs given):
Train number (0 to stop): 12951
12951: Coastal Express (found in 2 steps)
Train number (0 to stop): 11111
11111: no such train (3 steps)
Train number (0 to stop): 0
⚙️ C — you can edit this code

⚠️ Common mistakes (and how to fix them)

❌ Wrong

#include <stdio.h>

int search(const int a[], int n, int x) {
    for (int i = 0; i < n; i++) {
        if (a[i] == x) return i;
        else return -1;
    }
    return -1;
}

int main(void) {
    int a[] = { 5, 8, 13 };
    printf("13 is at %d\n", search(a, 3, 13));
    return 0;
}

Compiles and runs, but prints: 13 is at -1 ⏎

✅ Right

#include <stdio.h>

int search(const int a[], int n, int x) {
    for (int i = 0; i < n; i++) {
        if (a[i] == x) return i;
    }
    return -1;
}

int main(void) {
    int a[] = { 5, 8, 13 };
    printf("13 is at %d\n", search(a, 3, 13));
    return 0;
}

The else returns -1 right after checking the first item, so the loop never gets to the rest. Say "not found" only AFTER the loop has checked everything.

❌ Wrong

int a[] = { 10, 20, 30 };
int low = 0, high = 2, pos = -1;
while (low < high) {
    int mid = low + (high - low) / 2;
    if (a[mid] == 30) { pos = mid; break; }
    if (a[mid] < 30) low = mid + 1; else high = mid - 1;
}
printf("%d\n", pos);

Compiles and runs, but prints: -1 ⏎

✅ Right

int a[] = { 10, 20, 30 };
int low = 0, high = 2, pos = -1;
while (low <= high) {
    int mid = low + (high - low) / 2;
    if (a[mid] == 30) { pos = mid; break; }
    if (a[mid] < 30) low = mid + 1; else high = mid - 1;
}
printf("%d\n", pos);

When low equals high, one item is still left to check. With < the loop stops too early and misses it. Use <=.

❌ Wrong

int a[] = { 3, 6, 9 };
int target = 6, pos = -1;
for (int i = 0; i < 3; i++) {
    if (a[i] = target) { pos = i; break; }
}
printf("%d\n", pos);

Line 4: warning: using the result of an assignment as a condition without parentheses [-Wparentheses]

✅ Right

int a[] = { 3, 6, 9 };
int target = 6, pos = -1;
for (int i = 0; i < 3; i++) {
    if (a[i] == target) { pos = i; break; }
}
printf("%d\n", pos);

= puts target INTO a[i] (and the result 6 counts as true), so the first item always "matches" and the array is changed. Compare with ==. Clang warns about this.

📌 Remember

  • Linear search checks items one by one; it works on any array but is O(n).
  • Binary search needs a sorted array and halves the range each step: O(log n).
  • Use low <= high, and move low to mid + 1 or high to mid - 1.
  • About 20 binary-search steps are enough for a million items.
  • bsearch in <stdlib.h> does binary search for you with a compare function.

Finished the quiz and the challenge?

Questions students ask

Why does binary search need a sorted array?

Each step throws away half the array, assuming everything on one side is smaller and everything on the other side is bigger. That is only true if the array is sorted.

When should I use linear search instead of binary search?

Use linear search for small arrays, for unsorted data you search only once, or for linked lists, where you cannot jump to the middle. Use binary search when the data is sorted and you search it many times.

What is the time complexity of binary search?

O(log n). Doubling the size of the array adds only one more step. Linear search is O(n): doubling the size doubles the work.

Is there something faster than binary search?

Hash tables can find an item in about one step on average, by turning the key into an index. They use more memory and do not keep the data sorted. You will meet them in C++ as unordered_map.