Searching Algorithms in Data Structure: Types and Comparison

Data Structure / Chapter 36 / Search Atlas

Searching Algorithms in Data Structure: Types & Comparison

How does a computer find one value among hundreds of elements? Learn searching techniques from simple linear scans to fast binary search, complete C programs, interactive dry runs, and exam-focused comparisons.

Linear & Binary Search 6 Searching Techniques Runnable C Programs Visual Search Lab
Quick Answer / Exam Definition

Searching algorithms are step-by-step methods used to locate a required element (search key) in a collection of data. Linear search checks elements one by one and can work on unsorted arrays. Binary search repeatedly halves the search range but needs data sorted by the same comparison rule. Searching methods differ in speed, memory usage and input requirements.

Think about finding a student's roll number in a list. If the names are randomly arranged, you may check them one at a time. If the roll numbers are sorted, you can open the middle of the list and quickly eliminate half of the remaining entries. These two everyday approaches explain linear search and binary search in data structure .

We will first understand how searching works, then study sequential search, binary search, sentinel search, jump search, interpolation search and exponential search . We will also see where hashing and tree searching fit in. To understand what an algorithm means before reading pseudocode, revise Algorithm in Data Structure: Characteristics, Steps and Examples .

Chapter roadmap — show all sections
  1. Meaning and basic terms
  2. Types of searching methods
  3. Linear search explained
  4. Binary search explained
  5. Worked dry-run tables
  6. Interactive searching simulator
  7. Algorithms and pseudocode
  8. Complete C programs
  9. Other search techniques
  10. Complexity and comparison
  11. Applications and selection
  12. Common mistakes
  13. Solved exam questions
  14. MCQs, FAQs and revision
01 / First understand the purpose

What Is Searching in Data Structure?

Searching Algorithms in Data Structure: Types and Comparison

Searching is the process of finding whether a required value is present in a collection and, when found, locating its index, position or associated record. The required value is called the search key, target or element to be searched.

For example, if an array contains [12, 18, 25, 31, 44] and the search key is 31, the algorithm should return index 3 when indexing starts from zero. The human-readable position is fourth. If the target is 50, the algorithm must clearly report not found.

Successful Search

The key exists. Output may be its index, pointer, record or boolean value. Example: find 25 in [12, 25, 40] → index 1.

Unsuccessful Search

The key does not exist. A common C convention is to return -1. Example: find 70 in [12, 25, 40] → -1.

The best method depends on whether data is sorted, the collection size, how often searching happens, and whether insertion and deletion are also frequent.

02 / Understand the family

Types of Searching Algorithms in Data Structure

Introductory Data Structure courses usually focus on linear (sequential) search and binary search. Other array-searching techniques are useful for learning how information about the data can reduce work.

Basic / Unsorted okay

Linear or Sequential Search

Compares the search key with elements in order until it finds a match or finishes the array. Sorting is not required.

Basic / Sorted required

Binary Search

Checks the middle value and discards half the remaining search interval each step. Requires ordered, random-access data for standard array implementation.

Variation

Sentinel Search

Uses a temporary sentinel value to reduce repeated bounds checking in a linear scan. Worst-case time is still O(n).

Sorted / Block search

Jump Search

Moves through blocks, often of size about √n, and then scans the identified block. Worst-case O(√n) comparisons.

Sorted / Numeric keys

Interpolation Search

Estimates a likely position from the target's numeric value. Expected O(log log n) on suitably uniform distributions, but worst-case O(n).

Sorted / Expanding range

Exponential Search

Checks positions 1, 2, 4, 8 and so on to locate a range, then uses binary search inside it. O(log n) worst-case time.

Beyond arrays: Hash-table lookup has expected O(1) search under suitable hashing and load-factor assumptions, while balanced binary search trees give O(log n) worst-case search. They are separate structures/topics, not additional forms of binary search on an array.
03 / Search without sorting

Linear Search in Data Structure: Working and Example

Linear search (also called sequential search) begins at the first array element and compares it with the target. If they match, it returns the index. Otherwise, it moves to the next element until a match appears or the array ends.

Take this unsorted array: [27, 4, 48, 9, 63, 15, 34, 21]. To find 63, compare 27 → 4 → 48 → 9 → 63. The match occurs at index 4 after five comparisons.

01 23 45 67
27 4 48 9 63 153421
Linear search checks one value at a time. Target 63 is found at zero-based index 4.

Advantages: Very simple, needs no sorting, works on arrays and linked lists, and uses O(1) auxiliary space iteratively. Limitations: If the item is absent or near the end, it must inspect many or all n elements.

Complexity: Best O(1) when the first element matches; average and worst O(n), assuming a basic scan and typical target distributions. Even for a sorted array, plain linear search is still O(n) in the worst case.

04 / Halve the search space

Binary Search in Data Structure: Working and Example

Binary search works on an array sorted according to the same comparison used by the search. It maintains two indices, low and high, then calculates a middle index. If the middle value is too small, it searches the right part. If too large, it searches the left part.

mid = low + (high - low) / 2

This middle-index formula avoids possible integer overflow from (low + high) / 2 when indices are very large. Standard binary search assumes quick indexed access; linked lists do not offer the same random-access efficiency.

Consider sorted values [4, 9, 15, 21, 27, 34, 48, 63]. We want 27. First, low = 0 and high = 7; mid = 3, value 21. Because 27 is larger than 21, discard indices 0–3. Next mid = 5, value 34; discard indices 5–7. Finally mid = 4, value 27: found.

01 23 45 67
4 9 15 21 27 34 48 63
Binary search compares the middle of the remaining interval; target 27 is found in three comparisons.

Complexity: Best O(1), average and worst O(log n), and O(1) auxiliary space for an iterative array implementation. A recursive binary search normally uses O(log n) call-stack space.

Must remember: Binary search on an unsorted array is not valid. If you sort n items just to search once, the sorting cost must be included; the O(log n) claim assumes the sorted array is already available.
05 / Follow every comparison

Linear Search vs Binary Search: Step-by-Step Dry Run

Linear Search Dry Run: Find 34

StepIndex Element Compare with 34
1027Not equal; continue
214Not equal; continue
3248Not equal; continue
439Not equal; continue
5463Not equal; continue
6515Not equal; continue
7634Found at index 6

Binary Search Dry Run: Find 27

StepLow HighMid a[mid]Decision
107 321 27 > 21, low = 4
247 534 27 < 34, high = 4
344 427 Found at index 4

Unsuccessful case: Searching for 26 by binary search in the same sorted array eventually makes low > high; the answer is -1. A simple linear search returns -1 after checking every element. In both methods, the indices in our examples start at zero.

06 / Practice interactively

Interactive Searching Algorithms Visualizer

Select Linear Search or Binary Search, choose a target and follow comparisons one step at a time. Linear mode uses an unsorted array; binary mode uses its sorted version. The yellow cell marks a successful match, purple shows the current comparison and faded cells are already eliminated or checked.

Search Explorer Lab

0 comparisons

Select an algorithm, then start the search.

Range: waiting Result: waiting

Tip: Try targets 27, 63, 100 and 4.

Try this experiment: Search for 63 in each mode and compare the number of comparisons. The two arrays contain the same eight values but in different orders. Search for 100 to observe a proper not-found result. Changing the algorithm resets the current trace.
07 / Logic before programming

Linear and Binary Search Algorithms with Pseudocode

Linear Search Algorithm

  1. Read the array of n elements and the target key.
  2. Start at index 0 and compare with the target.
  3. If equal, return the index immediately (first occurrence).
  4. Otherwise move to the next index until n elements are checked.
  5. Return -1 if no match is found.
LINEAR_SEARCH(a, n, key): for i = 0 to n - 1: if a[i] == key: return i return -1

Binary Search Algorithm (Iterative)

  1. Make sure the array is sorted in ascending order.
  2. Set low = 0 and high = n - 1.
  3. While low <= high, calculate mid.
  4. If a[mid] equals key, return mid.
  5. If a[mid] is smaller, search right by low = mid + 1; otherwise search left by high = mid - 1.
  6. Return -1 after the interval becomes empty.
BINARY_SEARCH(a, n, key): low = 0; high = n - 1 while low <= high: mid = low + (high - low) / 2 if a[mid] == key: return mid if a[mid] < key: low = mid + 1 else: high = mid - 1 return -1

This standard binary search returns an occurrence when duplicates exist, not necessarily the first. To find the first occurrence, save a matching index and continue searching the left half; an implementation is given next.

08 / Complete executable programs

Searching Algorithms in C: Complete Programs with Output

These independent programs cover the two most important university-exam searching methods. They use fixed example arrays, print zero-based indices and return -1 when the value is absent. The binary search program additionally demonstrates how to find the first occurrence in a sorted array with duplicates .

Program 1: Linear Search in C

linear_search.c C11 / Complete program
#include <stdio.h>

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

int main(void) {
    int a[] = {27, 4, 48, 9, 63, 15, 34, 21};
    int n = (int)(sizeof a / sizeof a[0]);
    int key = 34;
    int index = linearSearch(a, n, key);

    if (index == -1) {
        printf("%d not found\n", key);
    } else {
        printf("%d found at index %d\n", key, index);
    }
    return 0;
}
34 found at index 6

Explanation: The loop examines index 0, then 1, then 2, and so on. At index 6 the element equals 34, so the function returns 6. If no element matches, it returns -1. This also works on unsorted data.

Program 2: Iterative Binary Search in C

binary_search.c C11 / Complete program
#include <stdio.h>

int binarySearch(const int a[], int n, int key) {
    int low = 0;
    int high = n - 1;

    while (low <= high) {
        int mid = low + (high - low) / 2;

        if (a[mid] == key) return mid;

        if (a[mid] < key) {
            low = mid + 1;
        } else {
            high = mid - 1;
        }
    }
    return -1;
}

int main(void) {
    int a[] = {4, 9, 15, 21, 27, 34, 48, 63};
    int n = (int)(sizeof a / sizeof a[0]);
    int key = 27;
    int index = binarySearch(a, n, key);

    if (index == -1) {
        printf("%d not found\n", key);
    } else {
        printf("%d found at index %d\n", key, index);
    }
    return 0;
}
27 found at index 4

Program 3: Recursive Binary Search in C

recursive_binary_search.c C11 / Complete program
#include <stdio.h>

int recursiveBinary(const int a[], int low,
                    int high, int key) {
    if (low > high) return -1;

    int mid = low + (high - low) / 2;

    if (a[mid] == key) return mid;
    if (a[mid] < key) {
        return recursiveBinary(a, mid + 1, high, key);
    }
    return recursiveBinary(a, low, mid - 1, key);
}

int main(void) {
    int a[] = {3, 7, 11, 19, 25, 31, 40};
    int n = (int)(sizeof a / sizeof a[0]);
    int key = 25;
    int index = recursiveBinary(a, 0, n - 1, key);

    printf("Index of %d: %d\n", key, index);
    return 0;
}
Index of 25: 4

Recursive versus iterative binary search: Both take O(log n) search time in the worst case, but recursive calls use O(log n) extra stack frames. The iterative version uses O(1) auxiliary space.

Program 4: First Occurrence with Binary Search in C

When a sorted array has duplicate values, a standard binary search may return any matching index. To return the first match, keep searching left after finding the key.

binary_search_first.c C11 / Complete program
#include <stdio.h>

int firstOccurrence(const int a[], int n, int key) {
    int low = 0, high = n - 1;
    int answer = -1;

    while (low <= high) {
        int mid = low + (high - low) / 2;

        if (a[mid] >= key) {
            if (a[mid] == key) answer = mid;
            high = mid - 1;
        } else {
            low = mid + 1;
        }
    }
    return answer;
}

int main(void) {
    int a[] = {2, 5, 5, 5, 8, 12};
    int n = (int)(sizeof a / sizeof a[0]);
    printf("First index of 5: %d\n",
           firstOccurrence(a, n, 5));
    return 0;
}
First index of 5: 1

Run in VS Code or a terminal: Save one program in its given filename. Use gcc -std=c11 -Wall -Wextra linear_search.c -o linear_search, then run ./linear_search; on Windows run linear_search.exe. Replace the filename and executable name for the other programs. Each program contains its own main(), so compile them separately.

09 / Beyond the two classics

Sentinel, Jump, Interpolation and Exponential Search

1. Sentinel Linear Search

Sentinel search places the target value temporarily at the end of a writable array, or in an extra available slot, so the inner loop only checks for a match. After scanning, the original value is restored. This can reduce bounds checks but does not change worst-case O(n) time. Do not overwrite read-only input; restore modified data safely before returning.

2. Jump Search

Jump search needs a sorted array. With n elements, it often jumps in blocks of around √n, identifies which block could contain the key, then performs linear search inside that block. For n = 16, a common step size is 4. It has O(√n) worst-case comparisons and O(1) auxiliary space for a basic iterative implementation.

3. Interpolation Search

Interpolation search estimates the target's likely position using the values at both ends, rather than always choosing the middle. It works on sorted numeric data and is most attractive when values are approximately uniformly distributed.

pos = low + (key - a[low]) * (high - low) / (a[high] - a[low])

This formula assumes the denominator is non-zero, and practical programs need careful bounds and overflow handling. Under suitably uniform distributions, expected search time may be O(log log n); on badly distributed values it can take O(n). Do not describe its best-case behaviour as a guarantee for every dataset.

4. Exponential Search

Exponential search also requires sorted data. Starting near index 1, it doubles the examined index (1, 2, 4, 8...) until passing the target or reaching the end. A binary search then runs in the identified interval. It takes O(log n) worst-case time and can be useful when the relevant prefix is much smaller than the entire available range.

Scope note: Fibonacci Search is another sorted-array method that narrows the interval using Fibonacci numbers. Its worst-case time is O(log n), but it is less commonly required than linear and binary search in introductory exams. Hash search and binary-search-tree search are broader data-structure-specific topics.
10 / Time-space comparison

Searching Algorithms Comparison Table: Time and Space Complexity

Let n be the number of array elements. The table assumes standard iterative implementations, and lists the auxiliary space beyond the input array, not the storage occupied by the input itself.

Searching method Input requirement Best time Average/expected Worst time Extra space
Linear Search Sorted or unsorted O(1) O(n) O(n) O(1)
Binary Search (iterative) Sorted, indexed O(1) O(log n) O(log n) O(1)
Sentinel Search Writable array / extra slot O(1) O(n) O(n) O(1)*
Jump Search Sorted, indexed O(1) O(√n) O(√n) O(1)
Interpolation Search Sorted numeric values O(1) O(log log n)** O(n) O(1)
Exponential Search Sorted, indexed O(1) O(log n) O(log n) O(1)

*Sentinel O(1) extra space assumes temporary in-place replacement or one available extra slot; copying the whole array changes memory cost. **Interpolation expected O(log log n) needs favourable, approximately uniform value distribution; not a universal average-case guarantee. Recursive binary search instead uses O(log n) stack space.

Why Does Binary Search Scale Better?

In the worst case, linear search can require about n comparisons. Binary search halves the active interval each time, requiring at most O(log n) comparisons. For an already sorted million-element array, binary search needs roughly twenty halving steps, while linear search might inspect close to a million items. This is a complexity illustration, not a benchmark of real runtime.

Linear growth

Double the input size → worst-case checks can roughly double. That is why linear search is O(n).

Logarithmic growth

Double the input size → binary search needs at most about one more halving step. That is why binary search is O(log n).

11 / Practical selection

Which Searching Algorithm Should You Use?

Unsorted or small list

Choose linear search for simplicity. Sorting before every one-off lookup is often unnecessary extra work.

Already sorted array

Choose binary search for reliable O(log n) search with O(1) extra space iteratively.

Sorted data, special pattern

Consider jump, exponential or interpolation search only when their assumptions fit the values and access pattern.

Many repeated lookups

Consider a hash table or balanced search tree depending on ordering, range queries, updates and worst-case requirements.

Real-life applications: Searching appears in roll-number lookup, contact lists, finding products by ID, locating a record in memory, searching a sorted dictionary, and retrieving information from databases. Real database systems use indexes and other access methods; they do not always perform simple linear or binary search directly on every stored row.

Searching is an operation on data structures, not one fixed structure itself. Related array-based and pointer-based operations also appear in Queue in Data Structure and Doubly Linked List in Data Structure , where locating an element can have different costs.

12 / Debugging mindset

Common Mistakes in Linear and Binary Search

  1. Applying binary search to an unsorted array: The left-versus-right decision becomes unreliable. Sort first or choose another method.
  2. Confusing position and index: Array index 0 means first position. In C, index 4 means fifth element.
  3. Using low < high accidentally: A standard inclusive binary search should use low <= high so a one-element interval is checked.
  4. Forgetting mid + 1 and mid - 1: Retaining the already-tested middle can cause an infinite loop.
  5. Thinking standard binary search returns the first duplicate: It may return any matching position. Use a left-bound variant to get the first.
  6. Mixing ascending and descending order: Reverse the comparison logic for descending-sorted arrays.
  7. Ignoring the cost of sorting: A single search after newly sorting unsorted input is not automatically faster overall.
  8. Reporting total array space as auxiliary space: Iterative linear and binary search use O(1) extra space, not O(n).
Memory trick: LINEAR = Look In Next Element And Repeat. BINARY = Begin In middle, Narrow Again Repeatedly. Most important exam line: Linear works without sorting; Binary needs sorting.
13 / Exam-ready solutions

Searching Algorithms Important Questions with Answers (2, 5, 10 Marks)

The following are original PYQ-style and university-exam-style practice questions, not verified questions from a named university's previous papers.

2 Marks / Short Answer

Q1. Define searching algorithm.

A searching algorithm is a finite set of steps for finding whether a required value exists in a data collection and returning its location or a not-found result.

Q2. Define linear search.

Linear search examines array elements sequentially until the search key matches or all elements have been checked.

Q3. What is the condition for binary search?

The input must be sorted according to the comparison being used. Standard efficient array binary search also assumes indexed random access.

Q4. Give the worst-case complexity of linear and binary search.

Linear search: O(n). Binary search on a sorted array: O(log n).

5 Marks / Explain with Example

Q5. Differentiate between linear and binary search.

Linear search checks elements one at a time and works with sorted or unsorted data, with worst-case O(n) time. Binary search checks the middle value and halves the active search interval. It needs a sorted array and takes O(log n) worst-case time. For example, to find 27 in [4, 9, 15, 21, 27, 34, 48, 63], binary search tests 21, then 34, then 27.

Q6. Explain best, average and worst cases in linear search.

Best case: key at the first index, one comparison, O(1). Worst case: key is absent or at the end, up to n comparisons, O(n). Average case under a typical uniformly distributed successful target assumes approximately (n + 1)/2 comparisons and is O(n).

Q7. Explain iterative vs recursive binary search.

Both divide the search interval by half and use O(log n) worst-case time. Iterative binary search updates low/high in a loop and requires O(1) auxiliary space. Recursive binary search makes another function call for the chosen half and uses O(log n) stack space.

10 Marks / Long Answer

Q8. Explain searching algorithms, types, programs and complexity.

Searching is used to locate a key in a set of values. Linear search performs sequential comparisons and does not need sorted data. Binary search requires sorted input and repeatedly halves the current search interval. Other searching methods include sentinel, jump, interpolation and exponential search. Draw one indexed array for linear search and one sorted-array halving diagram for binary search. Write their algorithms and complete C programs from Section 8. Compare linear O(n) worst-case time with binary O(log n), and explain that both iterative implementations require O(1) auxiliary space.

Q9. Trace binary search for target 27 in the sorted array.

Array: [4, 9, 15, 21, 27, 34, 48, 63]. Initially low = 0, high = 7, mid = 3, value 21. Since 27 > 21, low becomes 4. Next mid = 5, value 34; high becomes 4. Next mid = 4, value 27. Return index 4. There are three comparisons.

14 / Final revision

Searching Algorithms MCQs, FAQs and Quick Revision

Multiple-Choice Practice with Solutions

  1. Which searching algorithm works without sorting? A. Binary B. Linear C. Jump D. Interpolation. Answer: B. Linear search can inspect any order.
  2. Binary search worst-case time? A. O(n²) B. O(n) C. O(log n) D. O(1). Answer: C. Each step halves the interval.
  3. For n = 8, initial low = 0, high = 7, mid is: A. 3 B. 4 C. 7 D. 8. Answer: A. Integer division gives 3.
  4. Unsuccessful linear search returns what in our C programs? A. 0 B. -1 C. n D. 1. Answer: B. -1 means no matching index.
  5. Which technique jumps through sorted blocks? A. Sentinel B. Linear C. Jump D. Hash. Answer: C. Jump search finds a candidate block.
  6. Recursive binary search extra space? A. O(log n) B. O(n²) C. O(n) D. O(1). Answer: A. Stack depth grows logarithmically.
  7. Which technique estimates position from numeric values? A. Interpolation B. Sentinel C. Linear D. DFS. Answer: A. It estimates using value distribution.
  8. Does ordinary binary search always return the first duplicate? A. Yes B. No. Answer: B. A lower-bound variation is needed.

Frequently Asked Questions

What are the main types of searching algorithms in data structure?

Linear search and binary search are the two main introductory techniques. Sentinel, jump, interpolation, exponential and Fibonacci search are additional methods. Hash-table and tree searches are also used in broader data-structure applications.

Which is faster: linear search or binary search?

On a large already sorted indexed array, binary search usually requires far fewer comparisons asymptotically: O(log n) versus linear search's O(n) worst case. On a very small or unsorted list, linear search may be simpler or more appropriate.

Can binary search work on an unsorted array?

No. The usual half-discard decision requires data sorted by the same comparison. Sorting first has a cost that must be considered.

What is the difference between searching and sorting?

Searching locates a requested value; sorting arranges values into a chosen order. Binary search requires sorted data, but sorting is not itself a searching algorithm.

What is sequential search in C?

Sequential search is another name for linear search. It uses a loop to compare the target with each array element and returns the matched index or -1.

What is the space complexity of searching algorithms?

Iterative linear and binary search use O(1) auxiliary space. Recursive binary search uses O(log n) extra call-stack space. Other methods depend on their implementation and any copied data structures.

One-minute recap

Linear = compare one by one. Binary = compare middle and halve. Sorted data is required for binary search. A not-found search returns -1 in our C examples.

Exam formulas

Binary mid = low + (high - low)/2. Linear worst = O(n). Binary worst = O(log n). Iterative auxiliary space = O(1).

Chapter 36 / Completed

Conclusion: Choose the Right Search Strategy

Searching algorithms become easier when you ask two questions first: Is the data sorted? and How many elements may need checking? For unsorted data, linear search is a reliable starting point. For an already sorted array, binary search is generally a much more efficient choice as the size grows.

For university exams and coding interviews, practise both full C programs, trace low/mid/high carefully, remember the sorting precondition and learn the comparison table rather than memorising only the definitions.

Tags

Post a Comment

0 Comments
* Please Don't Spam Here. All the Comments are Reviewed by Admin.
Join Telegram Exam updates and free resources