Skip to main content
Data Structures
CHAPTER 28 Beginner

Search Algorithms (Linear & Binary)

Updated: May 17, 2026
15 min read

# CHAPTER 28

Search Algorithms (Linear & Binary)

1. Introduction

Every application on Earth requires searching. When you type a friend's name into Instagram, or scan a barcode at the grocery store, the software must locate a specific string of data inside a massive database array. In this chapter, we will study the two core algorithms used to search flat Arrays. We will begin with the primitive Linear Search, which checks every item one by one. Then, we will uncover the mathematical brilliance of Binary Search, an algorithm so powerful it can pinpoint a single target within 1 Billion records in a mere 30 steps.

2. Learning Objectives

By the end of this chapter, you will be able to:
  • Write a basic Linear Search using iteration.
  • Define the absolute physical prerequisite required to utilize Binary Search.
  • Execute the mathematical mid-point calculations of Binary Search.
  • Contrast O(n) Time Complexity vs O(log n) Time Complexity.

3. Linear Search (The Brute Force Approach)

Linear Search is the most primitive algorithm imaginable. It starts at index [0] and iteratively checks every single element sequentially until it either finds the target or hits the end of the array.

The Mechanics: Array: [14, 2, 7, 90, 5] Target: 90

  • Is [0] == 90? No.
  • Is [1] == 90? No.
  • Is [2] == 90? No.
  • Is [3] == 90? Yes! Return index 3.

java
123456789
// Java Example: Linear Search
public int linearSearch(int[] arr, int target) {
    for (int i = 0; i < arr.length; i++) {
        if (arr[i] == target) {
            return i; // Target found! Return the index instantly.
        }
    }
    return -1; // Loop finished without finding it. Return -1 (Error).
}

Complexity:

  • Worst Case: O(n). If the array has 1 Million items, and the target is at the very end (or doesn't exist), the CPU must execute 1 Million checks.

4. Binary Search (The Logarithmic Powerhouse)

If you are looking for the word "Zebra" in a 1,000-page physical dictionary, do you start at page 1 and read every single word sequentially? No! You physically split the book in half, see that you are on "M", and realize "Zebra" MUST be in the right half. You instantly throw away the left 500 pages. This is Binary Search.

#### The Absolute Prerequisite Binary Search CANNOT operate on randomized data. The array MUST BE PERFECTLY SORTED (e.g., using Merge Sort or Quick Sort) before you can run Binary Search!

The Mechanics: Sorted Array: [2, 5, 8, 12, 16, 23, 38, 56, 72, 91] Target: 23

  1. 1. Calculate Midpoint: The array has 10 elements. Midpoint is 16.
  1. 2. Compare: Is 23 == 16? No.
  1. 3. Eliminate: Is 23 > 16? YES! Because the array is sorted, 23 cannot possibly exist on the left side. We completely eliminate [2, 5, 8, 12, 16].
  1. 4. Repeat: The remaining array is [23, 38, 56, 72, 91]. Find the new midpoint (56). Is 23 < 56? Yes. Eliminate the right side.
  1. 5. Found: Midpoint is 23. Target acquired!

python
12345678910111213141516171819202122
# Python Example: Binary Search (Iterative)
def binary_search(arr, target):
    left = 0              # Start pointer
    right = len(arr) - 1  # End pointer

    while left <= right:
        # Calculate the mathematical center index
        mid = (left + right) // 2 

        # Case 1: Target found at the center!
        if arr[mid] == target:
            return mid

        # Case 2: Target is LARGER. Discard the entire Left half.
        elif arr[mid] < target:
            left = mid + 1

        # Case 3: Target is SMALLER. Discard the entire Right half.
        else:
            right = mid - 1

    return -1 # Target absolutely does not exist.

5. Complexity Analysis (O(log n) vs O(n))

The power of Binary Search is derived from mathematically discarding 50% of the remaining search space on every single loop iteration.
  • If N = 100, Linear Search takes 100 steps. Binary Search takes 7 steps.
  • If N = 1,000,000, Linear Search takes 1 Million steps. Binary Search takes 20 steps.
  • If N = 4 Billion, Linear Search takes 4 Billion steps. Binary Search takes 32 steps.

Binary Search is explicitly O(log n) Time Complexity.

6. The Midpoint Calculation Bug (Advanced)

Look at the formula mid = (left + right) / 2. For decades, computer science textbooks taught this formula. However, in massive enterprise systems where arrays have billions of elements, if left = 2 Billion and right = 2 Billion, adding them equals 4 Billion. This instantly exceeds the 32-bit Integer maximum limit (2.14 Billion), causing a catastrophic Integer Overflow Crash.

*The Senior Developer Solution:* mid = left + ((right - left) / 2) This advanced mathematical formula achieves the exact same midpoint, but strictly avoids large addition, making it completely immune to Overflow crashes!

7. Real-World Applications

  1. 1. Database Queries: When you execute SELECT * FROM users WHERE id = 500, MySQL does not linearly scan the hard drive. It utilizes a B-Tree structure to execute Binary Search logic, retrieving the user in milliseconds.
  1. 2. Git Bisect: If a developer introduced a bug 500 commits ago, git bisect uses Binary Search to jump to commit 250. If it's bug-free, it jumps to commit 375, finding the exact broken code in 9 steps!

8. Common Mistakes

  • Running Binary Search on Unsorted Data: If the array is [10, 2, 5], and you check the midpoint 2, the algorithm might assume the target 10 is on the right because 10 > 2. But 10 is actually on the left! The logarithmic routing logic shatters completely if the numbers are not perfectly sequential.

9. Exercises

  1. 1. Trace Binary Search looking for the number 7 in the sorted array [1, 3, 5, 7, 9, 11]. What are the values of left, right, and mid on the first iteration?
  1. 2. If an array is completely chaotic and unsorted, is it faster to run Linear Search, or is it faster to sort the array with Merge Sort and then run Binary Search? *(Hint: Look at Time Complexities).*

10. MCQs with Answers

Question 1

What is the execution mechanism of the primitive Linear Search algorithm?

Question 2

What is the absolute, uncompromising prerequisite condition that an array MUST satisfy before a Binary Search algorithm can be safely executed against it?

Question 3

How does Binary Search mathematically achieve its devastating execution speed?

Question 4

What is the theoretical Worst-Case Time Complexity of Binary Search?

Question 5

In a highly chaotic, entirely unorganized array, what is the required Time Complexity to locate a specific target?

Question 6

If an enterprise database executes Binary Search to locate a record within 4 Billion sorted rows, approximately how many maximum loop iterations will the CPU execute?

Question 7

What catastrophic software vulnerability exists in the traditional midpoint calculation formula mid = (left + right) / 2 when operating on massive global arrays?

Question 8

Which mathematically equivalent formula do Senior Engineers deploy to explicitly bypass the Integer Overflow vulnerability during midpoint calculation?

Question 9

If a developer uses a while(left <= right) loop constraint in Binary Search, what specific programmatic state signifies that the target absolutely does not exist in the dataset?

Question 10

Can Binary Search be written recursively instead of iteratively?

11. Interview Preparation

Top Interview Questions:
  • *Algorithmic Coding:* "Given a sorted array that has been mysteriously rotated at a random pivot (e.g., [4, 5, 6, 7, 0, 1, 2]), write an O(log n) algorithm to find a target." *(Answer: The legendary LeetCode 'Search in Rotated Sorted Array'. You must use a heavily modified Binary Search to detect which half of the split array is normally sorted before shifting your boundary pointers!).*

12. FAQs

Q: If Binary Search is so fast, should I just use MergeSort on my data first, and then use Binary Search? A: Be careful with the math! Merge Sort takes O(n log n). Linear Search only takes O(n). If you are only searching the array ONE time, sorting it first is actually slower! You only sort an array if you plan on running Binary Search on it thousands of times.

13. Summary

The contrast between Linear Search and Binary Search perfectly encapsulates the power of algorithmic theory. By organizing the physical structure of our data beforehand, we can execute mathematical logarithmic division, transforming an impossible 4-Billion step crawl into an instantaneous 32-step calculation.

14. Next Chapter Recommendation

We have mastered manipulating data structures. But some coding problems require complex mathematical formulas, exploring thousands of overlapping pathways (like calculating the Fibonacci sequence). In Chapter 29: Dynamic Programming, we will unlock the ultimate FAANG interview skill: Memoization and Tabulation.

Finish this Chapter

Save your progress on your learning path and prepare for coding interview challenges.

Discussion

Join the discussion

Log in or create a free account to participate.

Sort: ·