Table of Contents

    Searching in Array

    Programming Mastery

    Searching in Array

    Learn how to find a specific value inside an array using searching techniques such as linear search and binary search.

    What is Searching in Array?

    Searching in array means finding whether a specific value exists inside an array or not.

    The value we want to find is usually called the target value, search key, or simply key.

    Searching in an array is the process of checking array elements to find the position of a required value.

    For example, suppose we have an array of numbers:

    numbers = [10, 20, 30, 40, 50]

    If we want to search for 30, the program should check the array and tell us that 30 exists at index 2.

    Target = 30
    Found at index = 2

    Easy Real-Life Example

    Searching as Finding a Name in a Contact List

    Imagine you have a contact list on your phone. When you search for a friend's name, the phone checks the list and finds whether that name exists.

    Searching in an array works in a similar way. The program checks array elements and tries to match them with the target value.

    names = ["Aman", "Riya", "Sohan", "Meera"]
    
    Search Target = "Sohan"
    
    Result = Found at index 2

    Why is Searching Needed?

    Searching is one of the most common operations in programming because real-world applications often need to find data quickly.

    Searching is Used For

    • Finding a student name in a list.
    • Checking whether a product exists in inventory.
    • Finding a specific mark or score.
    • Checking whether a username already exists.
    • Finding an employee ID.
    • Searching a book in a library system.
    • Checking whether a number exists in a dataset.
    • Finding the position of an element in an array.
    Key Idea: Searching helps a program locate required data from a collection of values.

    Important Terms in Array Searching

    Term Meaning Example
    Array A collection of values stored under one name. [10, 20, 30]
    Target / Key The value we want to search for. 30
    Index The position of an element in the array. 0, 1, 2
    Found The target value exists in the array. 30 found
    Not Found The target value does not exist in the array. 99 not found

    Types of Searching in Array

    There are many searching algorithms, but beginners usually start with two important methods:

    Common Searching Methods

    • Linear Search: Checks elements one by one.
    • Binary Search: Searches efficiently by repeatedly dividing a sorted array into halves.

    Linear Search

    Linear search is the simplest searching technique. It checks each element of the array one by one from the beginning to the end.

    If the target value is found, the search stops and returns the index. If the target is not found after checking all elements, the result is not found.

    Linear search is also called sequential search because it checks elements sequentially.

    Linear Search Steps

    • Start from the first element.
    • Compare the current element with the target value.
    • If both are equal, return the index.
    • If not equal, move to the next element.
    • Repeat until the target is found or the array ends.
    • If the array ends without a match, return -1 or display not found.

    Linear Search Pseudocode

    FUNCTION linearSearch(array, target)
        FOR index FROM 0 TO length(array) - 1
            IF array[index] == target THEN
                RETURN index
            END IF
        END FOR
    
        RETURN -1
    END FUNCTION

    Example 1: Linear Search in Number Array

    /*
    This program searches for a number using linear search.
    */
    
    ENTRY POINT
        DECLARE numbers AS ARRAY = [10, 20, 30, 40, 50]
        DECLARE target AS INTEGER = 30
        DECLARE position AS INTEGER = -1
    
        FOR index FROM 0 TO length(numbers) - 1
            IF numbers[index] == target THEN
                SET position = index
                BREAK
            END IF
        END FOR
    
        IF position != -1 THEN
            DISPLAY target + " found at index " + position
        ELSE
            DISPLAY target + " not found"
        END IF
    END ENTRY POINT

    Expected Output

    30 found at index 2

    Example 2: Linear Search in Text Array

    /*
    This program searches for a student name in an array.
    */
    
    ENTRY POINT
        DECLARE names AS ARRAY = ["Aman", "Riya", "Sohan", "Meera"]
        DECLARE targetName AS TEXT = "Sohan"
        DECLARE isFound AS BOOLEAN = false
    
        FOR index FROM 0 TO length(names) - 1
            IF names[index] == targetName THEN
                SET isFound = true
                DISPLAY targetName + " found at index " + index
                BREAK
            END IF
        END FOR
    
        IF isFound == false THEN
            DISPLAY targetName + " not found"
        END IF
    END ENTRY POINT

    Expected Output

    Sohan found at index 2

    Linear Search Trace Table

    Suppose we search for 40 in the array:

    numbers = [10, 20, 30, 40, 50]
    target = 40
    Step Index Current Value Comparison Result
    1 0 10 10 == 40 Not matched
    2 1 20 20 == 40 Not matched
    3 2 30 30 == 40 Not matched
    4 3 40 40 == 40 Matched

    The target 40 is found at index 3.

    Linear Search Complexity

    Case Explanation Time Complexity
    Best Case Target is found at the first index. O(1)
    Average Case Target is found somewhere in the middle. O(n)
    Worst Case Target is at the last index or not present. O(n)

    Binary Search

    Binary search is a faster searching technique, but it works only when the array is sorted.

    Binary search checks the middle element first. If the target is smaller than the middle value, it searches the left half. If the target is greater than the middle value, it searches the right half.

    Important: Binary search requires the array to be sorted.

    Binary Search Steps

    • Set low to the first index.
    • Set high to the last index.
    • Find the middle index.
    • Compare the middle element with the target.
    • If equal, return the middle index.
    • If target is smaller, search the left half.
    • If target is larger, search the right half.
    • Repeat until the target is found or the search range becomes empty.

    Binary Search Pseudocode

    FUNCTION binarySearch(array, target)
        DECLARE low AS INTEGER = 0
        DECLARE high AS INTEGER = length(array) - 1
    
        WHILE low <= high DO
            DECLARE middle AS INTEGER = (low + high) DIV 2
    
            IF array[middle] == target THEN
                RETURN middle
            ELSE IF target < array[middle] THEN
                SET high = middle - 1
            ELSE
                SET low = middle + 1
            END IF
        END WHILE
    
        RETURN -1
    END FUNCTION

    Example 3: Binary Search in Sorted Array

    /*
    This program searches for a number using binary search.
    The array must be sorted.
    */
    
    ENTRY POINT
        DECLARE numbers AS ARRAY = [10, 20, 30, 40, 50, 60, 70]
        DECLARE target AS INTEGER = 50
    
        DECLARE low AS INTEGER = 0
        DECLARE high AS INTEGER = length(numbers) - 1
        DECLARE position AS INTEGER = -1
    
        WHILE low <= high DO
            DECLARE middle AS INTEGER = (low + high) DIV 2
    
            IF numbers[middle] == target THEN
                SET position = middle
                BREAK
            ELSE IF target < numbers[middle] THEN
                SET high = middle - 1
            ELSE
                SET low = middle + 1
            END IF
        END WHILE
    
        IF position != -1 THEN
            DISPLAY target + " found at index " + position
        ELSE
            DISPLAY target + " not found"
        END IF
    END ENTRY POINT

    Expected Output

    50 found at index 4

    Binary Search Trace Table

    Suppose we search for 50 in the sorted array:

    numbers = [10, 20, 30, 40, 50, 60, 70]
    target = 50
    Step low high middle numbers[middle] Action
    1 0 6 3 40 Target is greater, search right half.
    2 4 6 5 60 Target is smaller, search left half.
    3 4 4 4 50 Target found.

    Binary Search Complexity

    Case Explanation Time Complexity
    Best Case Target is found at the middle position immediately. O(1)
    Average Case Search range is divided repeatedly. O(log n)
    Worst Case Target is found after repeated halving or not found. O(log n)

    Linear Search vs Binary Search

    Feature Linear Search Binary Search
    Array Requirement Works on unsorted and sorted arrays. Requires sorted array.
    Searching Style Checks elements one by one. Checks middle and removes half of search space.
    Complexity O(n) O(log n)
    Difficulty Very easy. Moderate.
    Best For Small or unsorted arrays. Large sorted arrays.

    When to Use Which Search?

    Use Linear Search When

    • The array is not sorted.
    • The array is small.
    • You want a simple solution.
    • You are searching only once.

    Use Binary Search When

    • The array is sorted.
    • The array is large.
    • You need faster searching.
    • You may search many times in the same sorted data.

    Example 4: Search and Return True or False

    /*
    This function returns true if target exists, otherwise false.
    */
    
    FUNCTION containsValue(array, target)
        FOR index FROM 0 TO length(array) - 1
            IF array[index] == target THEN
                RETURN true
            END IF
        END FOR
    
        RETURN false
    END FUNCTION
    
    ENTRY POINT
        DECLARE numbers AS ARRAY = [5, 10, 15, 20]
        DECLARE result AS BOOLEAN = containsValue(numbers, 15)
    
        IF result == true THEN
            DISPLAY "Value exists"
        ELSE
            DISPLAY "Value does not exist"
        END IF
    END ENTRY POINT

    Expected Output

    Value exists

    Example 5: Count Occurrences of a Value

    Sometimes, the target value may appear multiple times in an array. In that case, we can count how many times it appears.

    /*
    This program counts how many times a target value appears.
    */
    
    ENTRY POINT
        DECLARE numbers AS ARRAY = [10, 20, 10, 30, 10, 40]
        DECLARE target AS INTEGER = 10
        DECLARE count AS INTEGER = 0
    
        FOR index FROM 0 TO length(numbers) - 1
            IF numbers[index] == target THEN
                SET count = count + 1
            END IF
        END FOR
    
        DISPLAY target + " appears " + count + " times"
    END ENTRY POINT

    Expected Output

    10 appears 3 times

    Common Beginner Mistakes

    Mistakes

    • Forgetting that indexes usually start from 0.
    • Using binary search on an unsorted array.
    • Not handling the case where the target is not found.
    • Using index <= length instead of index < length.
    • Returning the value instead of the index when the question asks for position.
    • Forgetting to use BREAK after finding the target in linear search.
    • Incorrectly updating low and high in binary search.
    • Confusing middle index with middle value.

    Better Habits

    • Always check valid indexes.
    • Use linear search for unsorted arrays.
    • Use binary search only for sorted arrays.
    • Return a clear not-found value such as -1.
    • Use meaningful variables such as target, position, low, high, and middle.
    • Test first index, last index, middle index, and missing values.
    • Use trace tables to understand search logic.
    • Keep search logic simple and readable.

    Best Practices for Searching in Array

    Recommended Practices

    • Clearly define the target value before searching.
    • Decide whether you need the index, value, count, or true/false result.
    • Use linear search when the array is unsorted.
    • Use binary search only when the array is sorted.
    • Return -1 or a clear message when the target is not found.
    • Use BREAK if only the first occurrence is needed.
    • Do not access indexes outside the array range.
    • Test with empty arrays, one-element arrays, and multiple-element arrays.
    • Use comments when the logic is not obvious.
    • Use trace tables for binary search practice.

    Prerequisites Before Learning Searching in Array

    Students should understand the following topics before learning array searching:

    Required Knowledge

    • Variables and constants.
    • Data types.
    • Comparison operators.
    • Conditions.
    • Loops and iteration.
    • Break statement.
    • Array indexing.
    • Array traversal.
    • Sorted and unsorted arrays.

    Practice Activity: Predict the Output

    Predict the output of the following pseudocode.

    numbers = [4, 8, 15, 16, 23, 42]
    target = 16
    position = -1
    
    FOR index FROM 0 TO length(numbers) - 1
        IF numbers[index] == target THEN
            SET position = index
            BREAK
        END IF
    END FOR
    
    DISPLAY position

    Your Answer

    Output:
    ________________________

    Sample Answer

    3

    Mini Quiz

    1

    What is searching in an array?

    Searching in an array means finding whether a target value exists in the array and identifying its position if needed.

    2

    What is linear search?

    Linear search is a method that checks array elements one by one until the target is found or the array ends.

    3

    What is binary search?

    Binary search is a searching method that works on sorted arrays by repeatedly dividing the search range into halves.

    4

    Can binary search be used on an unsorted array?

    No. Binary search requires the array to be sorted.

    5

    What value is commonly returned when a target is not found?

    A common not-found value is -1.

    Interview Questions on Searching in Array

    1

    Define searching in array.

    Searching in array is the process of locating a specific target value inside an array.

    2

    What is the difference between linear search and binary search?

    Linear search checks elements one by one, while binary search divides the search range into halves and works only on sorted arrays.

    3

    Which search is better for an unsorted array?

    Linear search is better for an unsorted array because it does not require sorting.

    4

    Why is binary search faster than linear search?

    Binary search is faster because it removes half of the remaining search space after each comparison.

    5

    What is the time complexity of linear search and binary search?

    Linear search has time complexity O(n), while binary search has time complexity O(log n).

    Quick Summary

    Concept Meaning
    Searching Finding a target value in an array.
    Target / Key The value we want to find.
    Linear Search Checks each element one by one.
    Binary Search Searches a sorted array by repeatedly dividing the range.
    Not Found Usually represented by -1 or a clear message.
    Linear Search Complexity O(n)
    Binary Search Complexity O(log n)

    Final Takeaway

    Searching in array is an essential programming operation used to find whether a specific value exists in a collection. Linear search is simple and works on unsorted arrays, while binary search is faster but requires sorted data. In the Programming Mastery Course, students should learn both methods because they build strong foundations for algorithms, problem-solving, and data structure concepts.