Tutorials Logic, IN info@tutorialslogic.com

Searching Algorithms Linear Search, Binary Search

Searching Algorithms Linear Search, Binary Search

Searching algorithms help you find whether a value exists in a collection and where it is located. Beginners usually start with linear search because it checks each item one by one, then move to binary search because it uses sorted data to remove half of the remaining search space after every comparison.

The important idea is not only the code, but the condition behind the code. Linear search works on unsorted or sorted arrays, but it may inspect every element. Binary search is much faster on large input, but it is correct only when the data is sorted and the left, right, and middle indexes are updated carefully.

Experienced developers use searching algorithms as building blocks for autocomplete, lookup tables, duplicate detection, range queries, and interview problems. A good implementation should define the input clearly, handle empty arrays, return a predictable result when the value is missing, and avoid off-by-one mistakes.

Once the basics are clear, searching becomes a way to reason about constraints. If the data is sorted, use the order. If the data is keyed, use a map. If the answer itself is monotonic, binary search may work even without directly searching an array.

Beginner View: What Searching Means

Searching means comparing a target value with values stored in a collection. If the target is found, the algorithm returns the position, the value, or a true/false answer depending on the problem. If the target is not found, it should return a clear failure value such as -1.

Before writing code, ask three questions: what collection am I searching, what exact value am I looking for, and what should happen when the value is absent? This habit makes the function easier to test.

  • Use linear search when the array is small or unsorted.
  • Use binary search when the array is sorted and random access is available.
  • Return a consistent not-found value so callers can handle the result safely.
  • Test the first element, last element, middle element, missing value, and empty array.

Linear Search Step by Step

Linear search starts at index 0 and compares each element with the target. It stops early if the target is found. If the loop finishes without a match, the target is not present.

This algorithm is simple and reliable because it does not need sorted data. Its time complexity is O(n), which means the number of comparisons grows in direct proportion to the number of elements.

  • Best case: the first element matches, so only one comparison is needed.
  • Worst case: the value is missing or at the last position, so every element is checked.
  • Space complexity is O(1) because no extra collection is required.

Binary Search Step by Step

Binary search keeps two boundaries: left and right. It checks the middle element. If the middle value is too small, the left boundary moves after the middle. If it is too large, the right boundary moves before the middle.

The repeated halving makes binary search O(log n). On one million sorted values, binary search needs about twenty comparisons, while linear search may need one million comparisons.

  • The array must be sorted according to the same rule used during comparison.
  • Use left <= right when both boundaries are inclusive.
  • Calculate middle safely as left + (right - left) / 2 in languages where integer overflow matters.
  • Move the correct boundary every loop or the algorithm can run forever.

Choosing the Right Search

Do not choose binary search automatically. If data changes constantly and is not sorted, sorting may cost more than a simple scan. If the same data is searched many times, sorting once and using binary search can be a strong design.

In real applications, you may also use hash maps for direct key lookup. Search algorithms still matter because they explain the tradeoff between preprocessing, memory, and lookup speed.

Algorithm Works On Time Best Use
Linear search Any array O(n) Small or unsorted data
Binary search Sorted array O(log n) Large sorted data
Hash lookup Key-value data Average O(1) Exact key lookup

Experienced Notes and Interview Thinking

Interview questions often hide binary search inside phrases like minimum possible answer, first true condition, lower bound, upper bound, rotated array, or search in answer space. The pattern is still about reducing the candidate range safely.

For production code, prefer readable boundary names and unit tests over clever one-line solutions. Searching bugs usually appear at edges: empty input, one item, duplicates, target outside the range, and boundaries that cross.

  • For duplicates, decide whether you need any match, first match, or last match.
  • For sorted objects, compare using the same key used for sorting.
  • For very large datasets, consider database indexes or search engines instead of scanning application memory.

Search Beyond Arrays

The same idea appears in databases, file systems, search boxes, and APIs. Indexes help databases avoid scanning every row. Hash maps help programs jump to a key. Search engines build specialized structures for text lookup.

Learning linear and binary search gives you the language to compare these systems. You can ask whether a lookup is scanning, using sorted order, using a hash, or using an index built ahead of time.

  • Use scanning when setup cost is not worth it.
  • Use indexes when the same lookup pattern happens often.
  • Use binary-search thinking for monotonic yes/no conditions.

Linear Search in C

This example returns the index of the target value or -1 when the target is missing.

Linear Search in C
#include <stdio.h>

int linearSearch(int arr[], int size, int target) {
    for (int i = 0; i < size; i++) {
        if (arr[i] == target) {
            return i;
        }
    }
    return -1;
}

int main() {
    int marks[] = {42, 65, 78, 91, 53};
    int size = sizeof(marks) / sizeof(marks[0]);
    int index = linearSearch(marks, size, 91);

    if (index == -1) {
        printf("Value not found\n");
    } else {
        printf("Value found at index %d\n", index);
    }

    return 0;
}
  • The loop stops immediately after a match, so it avoids unnecessary comparisons.
  • The same function works even if the array is not sorted.

Binary Search in C

Use binary search only after confirming that the array is sorted.

Binary Search in C
#include <stdio.h>

int binarySearch(int arr[], int size, int target) {
    int left = 0;
    int right = size - 1;

    while (left <= right) {
        int mid = left + (right - left) / 2;

        if (arr[mid] == target) {
            return mid;
        }
        if (arr[mid] < target) {
            left = mid + 1;
        } else {
            right = mid - 1;
        }
    }

    return -1;
}

int main() {
    int ids[] = {3, 8, 11, 19, 27, 35, 42};
    int index = binarySearch(ids, 7, 27);
    printf("Index: %d\n", index);
    return 0;
}
  • Each comparison removes half of the remaining values.
  • Changing only one boundary per iteration keeps the search range valid.

First Matching Position with Duplicates

Experienced problems often ask for the first occurrence, not just any occurrence.

First Matching Position with Duplicates
#include <iostream>
#include <vector>
using namespace std;

int firstOccurrence(const vector<int>& nums, int target) {
    int left = 0, right = (int)nums.size() - 1;
    int answer = -1;

    while (left <= right) {
        int mid = left + (right - left) / 2;
        if (nums[mid] >= target) {
            if (nums[mid] == target) answer = mid;
            right = mid - 1;
        } else {
            left = mid + 1;
        }
    }
    return answer;
}

int main() {
    vector<int> nums = {2, 4, 4, 4, 9, 12};
    cout << firstOccurrence(nums, 4) << '\n';
}
  • The search continues left after finding a match because an earlier duplicate may exist.
  • This is the foundation for lower-bound style interview questions.
Key Takeaways
  • Confirm whether the input is sorted before choosing binary search.
  • Define exactly what the function returns for found and not-found cases.
  • Test empty input, one item, first item, last item, duplicate values, and missing values.
  • Explain the time complexity and why the number of comparisons grows that way.
Common Mistakes to Avoid
Using binary search on unsorted data and trusting the result.
Forgetting to move left or right after checking the middle value.
Returning a found value when the caller needs the index.
Ignoring duplicates when the problem asks for first or last occurrence.

Practice Tasks

  • Write linear search for strings and return the first matching name.
  • Write binary search for a sorted array of prices.
  • Modify binary search to return the first value greater than or equal to the target.
  • Compare the number of comparisons made by linear search and binary search on 1000 values.

Frequently Asked Questions

Ready to Level Up Your Skills?

Explore 500+ free tutorials across 20+ languages and frameworks.