Table of Contents

    Searching Algorithms

    Chapter 18.9

    Searching Algorithms

    Learn what searching algorithms are, why searching is important in programming, how linear search and binary search work, when to use each searching technique, and how searching algorithms are used in real-world systems such as student records, product catalogs, contacts, files, databases, and websites.

    Introduction

    In programming, we often need to find a specific item from a collection of data. This process is called searching. For example, we may need to find a student by roll number, search a product by product code, find a contact by phone number, locate a file by name, or check whether a value exists in a list.

    A searching algorithm is a step-by-step method used to find a particular element from a collection of data. The collection may be an array, list, linked list, tree, graph, hash table, database table, or any other data structure.

    Searching is one of the most common operations in computer science. Almost every software application performs searching in some form. Search bars, login systems, file explorers, student management systems, e-commerce websites, databases, and social media platforms all use searching concepts.

    "A searching algorithm is a step-by-step process used to find a required element from a collection of data."

    Simple Definition of Searching Algorithm

    A searching algorithm is an algorithm that checks a collection of data to find whether a specific value exists and, if it exists, where it is located.

    In simple words:

    • Searching means finding data.
    • A searching algorithm gives steps to find data.
    • The target value is the value we want to find.
    • The data collection may be sorted or unsorted.
    • Different searching algorithms work differently.
    • The correct searching algorithm can make a program faster.
    SEARCHING CONCEPT
    Searching Algorithm = Data Collection + Target Value + Search Steps
    Important: Searching algorithms are used to find required information efficiently. The best searching method depends on the type of data structure and whether the data is sorted or unsorted.

    Why Do We Need Searching Algorithms?

    Searching algorithms are needed because real-world programs often work with large amounts of data. If a program searches data inefficiently, it may become slow and difficult to use.

    For example, imagine a school has 50,000 student records. If the system checks every record one by one every time a user searches for a student, it may become slow. A better searching algorithm or data structure can make the search much faster.

    Without Proper Searching Algorithm

    • Searching may become slow for large data.
    • Programs may check unnecessary records.
    • User experience may become poor.
    • Reports and filters may take more time.
    • Large applications may become inefficient.
    • System performance may decrease as data grows.

    With Proper Searching Algorithm

    • Required data can be found faster.
    • Programs become more efficient.
    • Large data can be handled better.
    • Search results can appear quickly.
    • Code becomes more structured and logical.
    • Application performance improves.

    Prerequisites

    Before learning searching algorithms, students should understand some basic programming and data structure concepts. These concepts help in understanding how search operations work internally.

    Prerequisite Topic Why It Is Needed
    Variables To store target values, indexes, and search results.
    Arrays / Lists Searching is commonly practiced first on arrays and lists.
    Loops Used to check elements one by one in many searching algorithms.
    Conditional Statements Used to compare the current element with the target value.
    Functions / Methods Searching logic is usually written as reusable functions.
    Sorted and Unsorted Data Some algorithms require sorted data, while others do not.
    Basic Time Complexity Helps compare which algorithm is faster for large data.

    Important Terms in Searching

    Before learning specific searching algorithms, it is useful to understand common terms used in searching.

    Term Meaning Example
    Data Collection The group of values where searching is performed. [10, 20, 30, 40]
    Target The value we want to find. 30
    Index The position of an element in an array or list. Index of 30 is 2
    Found Target value exists in the collection. 30 is found
    Not Found Target value does not exist in the collection. 50 is not found
    Sorted Data Data arranged in order. [10, 20, 30, 40]
    Unsorted Data Data not arranged in order. [30, 10, 40, 20]

    Types of Searching Algorithms

    There are many searching algorithms, but at beginner level, the two most important searching algorithms are:

    1

    Linear Search

    Checks elements one by one

    Linear search is the simplest searching algorithm. It starts from the first element and checks each element until the target is found or the list ends.

    2

    Binary Search

    Searches by repeatedly dividing sorted data

    Binary search works only on sorted data. It repeatedly checks the middle element and eliminates half of the remaining data.

    BEGINNER SEARCHING ALGORITHMS
    Searching = Linear Search + Binary Search

    Linear Search

    Linear search is the simplest searching algorithm. It checks each element one by one from the beginning until the target value is found.

    Linear search can work on both sorted and unsorted data. It does not require the data to be arranged in any particular order.

    LINEAR SEARCH RULE
    Check each element one by one

    Linear Search Example

    Suppose we have the following array:

    
    numbers = [15, 8, 22, 40, 10]
    target = 22
    

    Linear search checks:

    • Check 15: not target
    • Check 8: not target
    • Check 22: target found

    The target 22 is found at index 2.

    Linear Search Pseudocode

    
    function linearSearch(array, target):
    
        for i from 0 to array.length - 1:
    
            if array[i] == target:
                return i
    
        return -1
    

    If the target is found, the function returns the index. If the target is not found, it returns -1.

    Java Example: Linear Search

    Prerequisites: To understand this example, you should know arrays, loops, conditional statements, methods, and basic Java syntax.
    
    public class Main {
    
        static int linearSearch(int[] numbers, int target) {
    
            for (int i = 0; i < numbers.length; i++) {
    
                if (numbers[i] == target) {
                    return i;
                }
            }
    
            return -1;
        }
    
        public static void main(String[] args) {
    
            int[] numbers = {15, 8, 22, 40, 10};
            int target = 22;
    
            int result = linearSearch(numbers, target);
    
            if (result == -1) {
                System.out.println("Target not found");
            } else {
                System.out.println("Target found at index: " + result);
            }
        }
    }
    

    This program searches for 22 in the array. If it finds the value, it prints the index position.

    JavaScript Example: Linear Search

    Prerequisites: To understand this example, you should know JavaScript arrays, loops, functions, conditional statements, and console output.
    
    function linearSearch(numbers, target) {
    
        for (let i = 0; i < numbers.length; i++) {
    
            if (numbers[i] === target) {
                return i;
            }
        }
    
        return -1;
    }
    
    const numbers = [15, 8, 22, 40, 10];
    const target = 22;
    
    const result = linearSearch(numbers, target);
    
    if (result === -1) {
        console.log("Target not found");
    } else {
        console.log("Target found at index: " + result);
    }
    

    This JavaScript example follows the same logic as the Java example.

    Advantages of Linear Search

    Linear search is simple and easy to understand. It is commonly used as the first searching algorithm for beginners.

    Benefits of Linear Search

    • Very easy to understand.
    • Easy to implement.
    • Works on unsorted data.
    • Works on sorted data also.
    • Suitable for small collections.
    • No extra preparation is needed.
    • Can be used with arrays, lists, and linked lists.

    Limitations of Linear Search

    Linear search is simple, but it may be slow for large data because it checks elements one by one.

    Slow for Large Data If the target is near the end or not present, linear search may check every element.
    No Smart Skipping Linear search does not eliminate large portions of data like binary search.
    Time Increases with Data Size As the number of elements grows, the search time can grow significantly.

    Binary Search

    Binary search is a faster searching algorithm, but it has one important condition: the data must be sorted.

    Binary search works by checking the middle element of the sorted data. If the middle element is the target, the search is complete. If the target is smaller than the middle element, the search continues in the left half. If the target is greater than the middle element, the search continues in the right half.

    BINARY SEARCH RULE
    Check Middle then eliminate half
    Important: Binary search works correctly only when the data is sorted.

    Binary Search Example

    Suppose we have the following sorted array:

    
    numbers = [5, 10, 15, 20, 25, 30, 35]
    target = 25
    

    Binary search steps:

    • Middle element is 20.
    • Target 25 is greater than 20, so search the right half.
    • Right half is [25, 30, 35].
    • Middle element is 30.
    • Target 25 is less than 30, so search the left half.
    • Element 25 is found.

    Binary search avoids checking every element by reducing the search area each time.

    Binary Search Pseudocode

    
    function binarySearch(array, target):
    
        left = 0
        right = array.length - 1
    
        while left <= right:
    
            middle = (left + right) / 2
    
            if array[middle] == target:
                return middle
    
            else if target < arrayright = middle - 1
    
            else:
                left = middle + 1
    
        return -1
    

    If the target is found, the function returns the index. If the target is not found, it returns -1.

    Java Example: Binary Search

    Prerequisites: To understand this example, you should know arrays, loops, conditional statements, methods, sorted data, and basic Java syntax.
    
    public class Main {
    
        static int binarySearch(int[] numbers, int target) {
    
            int left = 0;
            int right = numbers.length - 1;
    
            while (left <= right) {
    
                int middle = (left + right) / 2;
    
                if (numbers[middle] == target) {
                    return middle;
                } else if (target < numbers[middle]) {
                    right = middle - 1;
                } else {
                    left = middle + 1;
                }
            }
    
            return -1;
        }
    
        public static void main(String[] args) {
    
            int[] numbers = {5, 10, 15, 20, 25, 30, 35};
            int target = 25;
    
            int result = binarySearch(numbers, target);
    
            if (result == -1) {
                System.out.println("Target not found");
            } else {
                System.out.println("Target found at index: " + result);
            }
        }
    }
    

    This program searches for 25 in a sorted array using binary search.

    JavaScript Example: Binary Search

    Prerequisites: To understand this example, you should know JavaScript arrays, loops, functions, conditional statements, sorted data, and console output.
    
    function binarySearch(numbers, target) {
    
        let left = 0;
        let right = numbers.length - 1;
    
        while (left <= right) {
    
            const middle = Math.floor((left + right) / 2);
    
            if (numbers[middle] === target) {
                return middle;
            } else if (target < numbers[middle]) {
                right = middle - 1;
            } else {
                left = middle + 1;
            }
        }
    
        return -1;
    }
    
    const numbers = [5, 10, 15, 20, 25, 30, 35];
    const target = 25;
    
    const result = binarySearch(numbers, target);
    
    if (result === -1) {
        console.log("Target not found");
    } else {
        console.log("Target found at index: " + result);
    }
    

    This JavaScript example uses Math.floor() to calculate the middle index.

    Advantages of Binary Search

    Binary search is much faster than linear search for large sorted data because it reduces the search area by half each time.

    Benefits of Binary Search

    • Very efficient for large sorted data.
    • Reduces search space by half each step.
    • Faster than linear search for large datasets.
    • Useful in sorted arrays and ordered data.
    • Important foundation for advanced algorithms.
    • Helps students understand divide-and-conquer thinking.

    Limitations of Binary Search

    Binary search is powerful, but it has some conditions and limitations.

    Requires Sorted Data Binary search does not work correctly on unsorted data.
    Not Ideal for Linked Lists Binary search needs quick middle access, which is easier in arrays than linked lists.
    Sorting Cost If data is unsorted, sorting it first may take extra time.
    More Complex Than Linear Search Beginners may need practice to understand left, right, and middle updates.

    Linear Search vs Binary Search

    Linear search and binary search are both used to find elements, but they work differently. Linear search checks one by one, while binary search divides sorted data into halves.

    Basis Linear Search Binary Search
    Data Requirement Works on sorted and unsorted data. Requires sorted data.
    Search Method Checks elements one by one. Checks middle and eliminates half.
    Speed Slower for large data. Faster for large sorted data.
    Implementation Very simple. Slightly more complex.
    Best Use Small or unsorted data. Large sorted data.
    Example Searching a small list of names. Searching a sorted list of roll numbers.

    Time Complexity Basics

    Time complexity helps us understand how the running time of an algorithm grows as the input size increases. For searching algorithms, time complexity helps compare how efficient they are.

    Algorithm Best Case Average Case Worst Case
    Linear Search O(1) O(n) O(n)
    Binary Search O(1) O(log n) O(log n)

    In simple terms, binary search grows much more slowly than linear search when data size increases.

    Beginner Tip: O(n) means the search may grow with the number of elements. O(log n) means the search grows much slower because the data is divided repeatedly.

    Searching in Different Data Structures

    Searching behavior depends on the data structure used. Some structures are better for searching than others.

    Data Structure Common Searching Method Explanation
    Array / List Linear Search or Binary Search Binary search works if the array is sorted.
    Linked List Linear Search Nodes are checked one by one.
    Hash Table / Dictionary Key Lookup Fast lookup using keys.
    Binary Search Tree Tree Search Move left or right based on comparison.
    Graph BFS or DFS Search connected vertices.
    Database Index-Based Search Indexes help find records faster.

    Real-World Example: Student Management System

    In a student management system, searching is used frequently. For example, users may search students by roll number, name, course, grade, or marks.

    Search Requirement Possible Searching Approach Reason
    Find student by roll number in unsorted list Linear Search Data is not sorted.
    Find roll number in sorted list Binary Search Sorted data allows faster search.
    Find student by unique ID Dictionary / Hash Table Key-based lookup is fast.
    Find students above 80 marks Linear scan or database query Multiple matching records may exist.
    Find connected students in a project group Graph Search Relationships are involved.

    Real-World Example: E-Commerce Search

    E-commerce websites use searching to help users find products. Users may search by product name, category, price range, brand, product ID, or availability.

    A simple product list may use linear search. A sorted price list may use binary search. A product ID lookup may use a hash table or database index.

    Real-World Example: Contact Search

    A mobile contact list allows users to search for a person by name or phone number. If contacts are stored alphabetically, searching can be optimized. If phone numbers are used as keys, dictionary-based lookup can be very fast.

    Real-World Example: File Search

    Operating systems allow users to search files by name, extension, size, date, or content. File search systems may use indexing to make searching faster instead of scanning every file every time.

    When Should You Use Linear Search?

    Linear search is useful when the data is small, unsorted, or when simplicity is more important than speed.

    Use Linear Search When

    • The data is unsorted.
    • The collection is small.
    • You need a simple solution.
    • You are searching a linked list.
    • You do not want to sort data first.
    • You need to find all matching elements, not just one.

    When Should You Use Binary Search?

    Binary search is useful when data is sorted and the collection is large enough that faster searching matters.

    Use Binary Search When

    • The data is sorted.
    • The collection is large.
    • You need faster searching.
    • You are using an array or structure with direct index access.
    • You frequently search the same sorted data.
    • You want to practice divide-and-conquer logic.

    Common Mistakes Beginners Make

    Searching algorithms are simple in concept, but beginners often make mistakes with indexes, sorted data, and loop conditions.

    Common Mistakes

    • Using binary search on unsorted data.
    • Forgetting to return -1 when target is not found.
    • Confusing index with value.
    • Using wrong loop condition in binary search.
    • Not updating left and right correctly.
    • Stopping search too early in linear search.
    • Not checking all elements when target is not found.
    • Assuming linear search is always bad.
    • Assuming binary search is always best.
    • Not considering data structure before choosing algorithm.

    Better Approach

    • Use linear search for unsorted data.
    • Use binary search only for sorted data.
    • Trace index values step by step.
    • Check left, right, and middle carefully.
    • Return clear result when target is not found.
    • Choose algorithm based on data size and structure.
    • Practice with small arrays first.
    • Understand the logic before memorizing code.

    Best Practices for Searching Algorithms

    Good searching logic should be simple, correct, and suitable for the data structure.

    Recommended Practices

    • Understand whether data is sorted or unsorted.
    • Use linear search for small or unsorted data.
    • Use binary search for sorted data with direct index access.
    • Use hash tables for fast key-based lookup.
    • Use meaningful variable names such as target, left, right, middle.
    • Handle the not-found case clearly.
    • Test searching at beginning, middle, end, and missing target cases.
    • Trace algorithm steps on paper before coding.
    • Do not use binary search unless data is sorted.
    • Choose searching method based on problem requirement.

    Mini Practice Activity

    Complete the following practice tasks to strengthen your understanding of searching algorithms.

    Task Description Expected Learning
    Task 1 Search for 30 in the array [10, 20, 30, 40, 50] using linear search. Understand element-by-element checking.
    Task 2 Search for 25 in the sorted array [5, 10, 15, 20, 25, 30] using binary search. Understand middle element checking.
    Task 3 Try binary search on an unsorted array and explain why it fails. Understand sorted data requirement.
    Task 4 Write linear search pseudocode in your own words. Practice algorithm writing.
    Task 5 Write binary search steps for finding 70 in [10, 20, 30, 40, 50, 60, 70]. Practice left, right, and middle updates.
    Task 6 Compare linear search and binary search using your own example. Practice choosing the correct algorithm.

    Frequently Asked Questions

    1. What is a searching algorithm?

    A searching algorithm is a step-by-step method used to find a specific element from a collection of data.

    2. What is linear search?

    Linear search is a searching algorithm that checks each element one by one until the target is found or the list ends.

    3. What is binary search?

    Binary search is a searching algorithm that works on sorted data by repeatedly checking the middle element and eliminating half of the search area.

    4. Which searching algorithm is easiest?

    Linear search is the easiest searching algorithm because it checks values one by one.

    5. Which searching algorithm is faster?

    Binary search is usually faster than linear search for large sorted data.

    6. Can binary search work on unsorted data?

    No. Binary search requires sorted data. If the data is unsorted, binary search may give incorrect results.

    7. What does target mean in searching?

    The target is the value that we want to find in the data collection.

    8. What should a search function return if the target is not found?

    Many search functions return -1 or a special message when the target is not found.

    9. What is the time complexity of linear search?

    The worst-case time complexity of linear search is O(n), because it may check every element.

    10. What is the time complexity of binary search?

    The worst-case time complexity of binary search is O(log n), because it divides the search space in half each time.

    Summary

    Searching algorithms are used to find a specific value from a collection of data. Searching is one of the most common operations in programming and is used in student records, product catalogs, contact lists, file systems, databases, websites, and many other applications.

    Linear search checks each element one by one and works on both sorted and unsorted data. It is simple and useful for small collections, but it can be slow for large datasets.

    Binary search works only on sorted data. It checks the middle element and eliminates half of the search area each time. It is much faster than linear search for large sorted arrays.

    Choosing the right searching algorithm depends on the data size, whether the data is sorted, and the data structure being used. A good programmer should understand both linear search and binary search clearly before moving to advanced searching techniques.

    Key Takeaway

    Searching algorithms help find required data from a collection. Linear search checks elements one by one and works on unsorted data. Binary search works on sorted data and searches faster by repeatedly dividing the search space in half.

    Practice Quiz 12 MCQs Smart Learning

    Master This Topic with Smart Practice

    Reinforce what you just learned by solving high-quality MCQs. Improve accuracy, boost confidence, and prepare like a topper.

    Topic-wise MCQs
    Instant Results
    Improve Accuracy
    Exam Ready Practice
    Login & Start Quiz Create Free Account
    Save progress • Track results • Learn faster