Linear Search in Data Structure: Algorithm & Time Complexity

Data Structure / Chapter 37 / Algorithm Case File

Linear Search in Data Structure: Algorithm & Time Complexity

One array. One target. A simple left-to-right investigation. Understand every comparison, write complete C programs, count real operations and master searching questions for university exams.

Sequential SearchC ProgramsO(n) ExplainedInteractive Trace
Quick Answer / Direct Definition

Linear Search (Sequential Search) is a searching algorithm that checks elements one by one from the beginning of a collection until it finds the required value or reaches the end. It works on sorted and unsorted arrays. Its best-case time is O(1), while average and worst-case time are O(n). Iterative array linear search uses O(1) auxiliary space.

Imagine searching for your roll number on a classroom noticeboard. If entries are in a random order, you begin with the first name, check it, then move to the next until you find yours. A computer performs the same task using a linear search algorithm.

This Chapter 37 is a focused practical guide to linear search in data structure: algorithm, pseudocode, flowchart, C implementation, first/last/all occurrences, sentinel variation, linked-list searching and detailed time-complexity calculations. For the wider comparison with binary, jump and interpolation search, see the earlier searching-algorithms overview if you have already read it. To revise what makes an algorithm correct, read Algorithm in Data Structure: Characteristics, Steps and Examples.

Open Chapter 37 roadmap
  1. Definition and terminology
  2. Working diagram and comparisons
  3. Algorithm and pseudocode
  4. Flowchart
  5. Successful and unsuccessful dry runs
  6. Time complexity derivation
  7. Space complexity and extra cases
  8. Interactive linear search lab
  9. C program: user input
  10. C program: duplicate values
  11. C program: sentinel search
  12. C program: linked list
  13. Linear vs binary and use cases
  14. Common mistakes
  15. Solved 2/5/10-mark questions
  16. MCQs, FAQs and revision
01 / Begin with meaning

What Is Linear Search in Data Structure?

Linear Search in Data Structure: Algorithm & Time Complexity

Linear Search, also known as Sequential Search, is a straightforward method of locating a value by comparing the search key with each element in order. A comparison either finds the value or tells us to continue. No special arrangement of elements is required.

Search key / Target

The value we want to find, such as roll number 42.

Index / Position

The location of an element. In C, indices start at 0, so index 3 means fourth position.

Successful search

The target is present. Our standard function returns the first matching index.

Unsuccessful search

The entire list is checked without a match. Our C functions return -1.

A simple array is enough: no sorting, tree or hash table is needed. Linear search also works naturally when scanning linked-list nodes from head to tail.

02 / Follow the evidence

How Does Linear Search Work? Visual Example

Consider the unsorted array [14, 28, 9, 42, 17, 35, 8]. The target is 42. Start at index 0 and compare each value with 42. The first three comparisons fail; the fourth succeeds.

0123456
142894217358
Gray = already checked, gold = match, remaining values = not checked. Output: index 3 after 4 comparisons.
  1. Compare a[0] = 14 with 42 → not equal.
  2. Compare a[1] = 28 with 42 → not equal.
  3. Compare a[2] = 9 with 42 → not equal.
  4. Compare a[3] = 42 with 42 → found; stop.
Important: Basic linear search returns as soon as it finds the first match. It does not automatically find every repeated value. To report all matches, continue scanning after the first success.
03 / Write an exam-ready algorithm

Linear Search Algorithm and Pseudocode

The standard algorithm below receives an array A, size n and key key. It returns the first matching zero-based index, or -1 when no match exists.

  1. Start and read array A, length n and search key.
  2. Set index i = 0.
  3. Compare A[i] with key while i < n.
  4. If equal, return i immediately.
  5. Otherwise increase i by 1 and repeat.
  6. If the loop finishes, return -1 (not found).
LINEAR_SEARCH(A, n, key) FOR i = 0 TO n - 1 IF A[i] == key RETURN i RETURN -1

Why it terminates: With every unsuccessful comparison, i increases by one. Because the array length is finite, the loop eventually finds a match or reaches n. An empty array (n = 0) immediately returns -1 without comparing any element.

04 / Flowchart in words and blocks

Linear Search Flowchart Explained

The following simple flow is mobile-friendly and can be copied into a handwritten flowchart during an exam. Use an oval for start/stop, a rectangle for assignments, a diamond for a condition and a parallelogram for output.

Not equal→i = i + 1→Repeat conditions
i < n? No→Return -1→STOP

At the comparison condition, the No branch goes back to the loop after incrementing i. At the length condition, the No branch ends with not found.

05 / Step-by-step dry run

Linear Search Dry Run: Found, Not Found and Duplicates

Example A: Successful Linear Search for 42

Comparisoni (index)A[i]A[i] == 42?Action
1014NoContinue
2128NoContinue
329NoContinue
4342YesReturn 3

Answer: Found at index 3, position 4; number of element comparisons = 4.

Example B: Unsuccessful Linear Search for 99

The array contains 7 values, none equal to 99. The algorithm compares 99 with 14, 28, 9, 42, 17, 35 and 8. After 7 comparisons, it returns -1. This is a typical worst-case example.

Example C: Duplicate Values

Array: [18, 42, 7, 18, 91, 35, 18]. Target: 18. Standard first-match linear search returns index 0 after one comparison. A full scan finds indices 0, 3 and 6 after examining all 7 elements. A last-occurrence scan returns index 6.

06 / Complexity derived, not memorised

Linear Search Time Complexity: Best, Average and Worst Case

Let n be the array length, and count only key comparisons A[i] == key. For a standard algorithm that returns on the first match, comparison count depends on the target's position.

CaseWhen?ComparisonsComplexity
BestFirst element matches1 for n > 0Θ(1), O(1)
Average (successful, uniform)Target equally likely at each index(n + 1) / 2Θ(n), O(n)
WorstLast element matches or key absentnΘ(n), O(n)
Empty arrayn = 00Θ(1) overall control work

Why is the successful average (n + 1) / 2?

Suppose a successful target is equally likely to occur in any of the n positions, with no duplicates affecting the first-match assumption. Comparisons can be 1, 2, 3, ... n. Their arithmetic average is:

Average comparisons = (1 + 2 + 3 + ... + n) / n = [n(n + 1) / 2] / n = (n + 1) / 2 For n = 7: (7 + 1) / 2 = 4 comparisons.

If you mix successful and unsuccessful searches, the precise average also depends on the chance of success. If that probability is p and successful positions are uniform, the expected key comparisons are p(n + 1)/2 + (1 - p)n. That remains O(n) for the usual model.

Why is worst-case O(n)?

When the key is missing, every one of the n items must be checked. Doubling n can approximately double the number of comparisons. Therefore a standard unsorted linear scan has linear time growth, expressed as O(n).

Big O, Omega and Theta: Big O expresses an upper bound, Omega a lower bound and Theta a tight bound. The best-case running time for first-match search is Θ(1), and the worst-case running time is Θ(n). Do not claim the worst case is O(1) because an early match is possible.
07 / Memory and variations

Space Complexity of Linear Search and Important Variants

Iterative, first-match search

Stores a fixed number of counters and the key: O(1) auxiliary space. The input array itself is not counted as extra space.

Recursive linear search

Uses a call for each checked element. Worst-case recursion depth is O(n), so extra stack space is O(n).

Count or last occurrence

Scan all n elements to count matches or save the last index. Time O(n); auxiliary space O(1).

Store all match indices

Scanning takes O(n), but storing k matches in a result array uses O(k) extra output space, where 0 ≤ k ≤ n.

Linear search for strings: In C, compare strings with strcmp() rather than ==. A string comparison itself may inspect several characters, so counting each element comparison as O(1) assumes constant-size keys. For very long strings, character-comparison cost also matters.

08 / Make every check visible

Interactive Linear Search Simulator: First, Last and All Matches

Try three types of sequential searching with the same array: [18, 42, 7, 18, 91, 35, 18]. Select First occurrence to stop early, or Last / All to scan everything. Enter 99 to see an unsuccessful search.

Search Detective Lab

0 comparisons
018
142
27
318
491
535
618

Ready. Press Start, then Next comparison.

Result: waitingChecked: 0 of 7

Purple = currently examined; gray = checked; gold = matching element. The simulator teaches linear search, not binary search.

Practice challenge: Find 18 using First, then Last, then All. Compare outputs and number of checks. In First mode the answer is index 0 in one comparison. In Last/All modes the full 7-element array is scanned to make the answer complete.
09 / C program 1

Linear Search in C Using Array and User Input

This complete program accepts up to 100 integers, takes a target, returns the first matching index and reports not found clearly. It also handles an empty array (n = 0). It is suitable for beginners practising linear search program in C with user input.

linear_search_input.cComplete C11 program
#include <stdio.h>
#define CAPACITY 100

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[CAPACITY];
    int n, key;

    printf("How many elements (0 to 100)? ");
    if (scanf("%d", &n) != 1 || n < 0 || n > CAPACITY) {
        puts("Invalid array length.");
        return 1;
    }

    for (int i = 0; i < n; i++) {
        printf("Element %d: ", i);
        if (scanf("%d", &a[i]) != 1) {
            puts("Invalid integer input.");
            return 1;
        }
    }

    printf("Enter target: ");
    if (scanf("%d", &key) != 1) {
        puts("Invalid target.");
        return 1;
    }

    int index = linearSearch(a, n, key);
    if (index == -1)
        printf("%d not found.\n", key);
    else
        printf("%d found at index %d (position %d).\n",
               key, index, index + 1);
    return 0;
}
How many elements (0 to 100)? 5 Element 0: 21 Element 1: 6 Element 2: 42 Element 3: 9 Element 4: 18 Enter target: 42 42 found at index 2 (position 3).

Code explanation: The for-loop visits array positions from 0 to n - 1. On equality it returns immediately, so duplicates lead to the first occurrence. If no comparison succeeds, the function returns -1.

Run on Windows/VS Code: Save as linear_search_input.c. With GCC installed, compile using gcc -std=c11 -Wall -Wextra linear_search_input.c -o linear_search_input, then run linear_search_input.exe in the terminal. Linux/macOS users can run ./linear_search_input.

10 / C program 2

Linear Search in C for First, Last and All Occurrences

What changes when the search key appears more than once? This program does not stop at the first match: it scans all elements once, counting matches and remembering first and last positions. It also prints every matching index without allocating a new result array.

linear_search_duplicates.cComplete C11 program
#include <stdio.h>

int main(void) {
    int a[] = {18, 42, 7, 18, 91, 35, 18};
    int n = (int)(sizeof a / sizeof a[0]);
    int key = 18;
    int first = -1, last = -1, count = 0;

    printf("Matching indices for %d: ", key);

    for (int i = 0; i < n; i++) {
        if (a[i] == key) {
            if (first == -1) first = i;
            last = i;
            count++;
            printf("%d ", i);
        }
    }

    printf("\nFirst index: %d\n", first);
    printf("Last index: %d\n", last);
    printf("Total occurrences: %d\n", count);
    return 0;
}
Matching indices for 18: 0 3 6 First index: 0 Last index: 6 Total occurrences: 3

The whole array is always scanned to guarantee the final count and last index. Therefore the loop performs n comparisons: Θ(n) time, with O(1) additional working memory (excluding output).

11 / C program 3

Sentinel Linear Search in C with Example

Sentinel search is a variation of linear search that temporarily puts the target at the final array position. This guarantees the scan will stop, allowing a loop without a separate index-bounds comparison at each iteration. Afterwards, it restores the original last value and checks whether the match was genuine.

sentinel_linear_search.cComplete C11 program
#include <stdio.h>

/* The array must be writable. */
int sentinelSearch(int a[], int n, int key) {
    if (n == 0) return -1;

    int last = a[n - 1];
    a[n - 1] = key;

    int i = 0;
    while (a[i] != key) {
        i++;
    }

    a[n - 1] = last;  /* Restore original data. */

    if (i < n - 1 || last == key) return i;
    return -1;
}

int main(void) {
    int a[] = {11, 25, 8, 34, 52};
    int n = (int)(sizeof a / sizeof a[0]);

    printf("Index of 34: %d\n",
           sentinelSearch(a, n, 34));
    printf("Index of 99: %d\n",
           sentinelSearch(a, n, 99));
    printf("Last element after search: %d\n", a[n - 1]);
    return 0;
}
Index of 34: 3 Index of 99: -1 Last element after search: 52

Careful: The function cannot safely change a read-only array or shared data being read concurrently. We must restore the original last element. Sentinel search still has O(n) worst-case time and O(1) extra space; it does not become binary search.

12 / C program 4

Linear Search Using Linked List in C

Linear search is not restricted to arrays. A normal singly linked list has no O(1) random-access index, so we start at head and follow next pointers until we find a matching node or reach NULL. Read Linked List in Data Structure: Types, Operations and Examples to revise node traversal.

linked_list_linear_search.cComplete C11 program
#include <stdio.h>

typedef struct Node {
    int data;
    struct Node *next;
} Node;

int searchList(const Node *head, int key) {
    int index = 0;

    while (head != NULL) {
        if (head->data == key) return index;
        head = head->next;
        index++;
    }
    return -1;
}

int main(void) {
    Node third = {30, NULL};
    Node second = {20, &third};
    Node first = {10, &second};

    printf("Index of 20: %d\n",
           searchList(&first, 20));
    printf("Index of 99: %d\n",
           searchList(&first, 99));
    return 0;
}
Index of 20: 1 Index of 99: -1

This example uses three locally declared nodes, so no dynamic allocation is needed. The searchList() function still runs in O(n) worst-case time and O(1) auxiliary space. With dynamically allocated nodes, the search logic is the same.

13 / Pick the correct search

Linear Search vs Binary Search and Practical Applications

FeatureLinear SearchBinary Search
Data orderSorted or unsortedMust already be sorted
StrategyScan elements one by oneHalve the remaining interval
Worst-case timeO(n)O(log n) on an indexed array
Best-case timeO(1)O(1)
Iterative extra spaceO(1)O(1)
Good forSmall/unsorted data; linked traversalLarge already-sorted arrays

Use linear search to find an ID in a small unsorted array, check a short list of allowed values, scan a linked list, locate the first duplicate, or inspect a temporary set of records. It is easy to implement and requires no preprocessing.

Limitations: The number of checks grows with input size. If there are many repeated searches on a large collection, organizing the data into a sorted array, index, hash table or search tree may improve performance. Sorting for one search has its own cost, so always consider the whole task rather than comparing O(n) and O(log n) alone.

When analysing searching on nodes, compare the array case with Linked List Representation Using Arrays and Pointers. That chapter explains why following next links remains sequential.

14 / Avoid these exam and code bugs

Common Mistakes in Linear Search Programs

  1. Off-by-one error: For an array of n elements, valid indices are 0 to n - 1; use i < n, not i <= n.
  2. Index versus position: If a function returns index 3, that is fourth position when counting from 1.
  3. Wrong not-found behaviour: Do not report not found from inside the loop after the first mismatch. Wait until every relevant element has been checked.
  4. Duplicates: A return inside the loop gives the first match; counting all matches requires scanning the whole array.
  5. Missing input validation: Check scanf() results and the maximum array length before reading input.
  6. Confusing input storage with extra space: An O(n)-size input array does not make the iterative algorithm's auxiliary space O(n).
  7. Assuming sorting is necessary: Plain sequential search works equally well with an unsorted array.
  8. Unsafe sentinel logic: Do not forget to restore the overwritten last value and check for n = 0.
Memory trick: LOOK → COMPARE → MOVE → STOP. If found, stop and return the index; if the list ends, return -1. Remember the complexity line: Best O(1), Average O(n), Worst O(n), Iterative Space O(1).
15 / University exam answers

Linear Search Important Questions with Answers (2, 5 and 10 Marks)

These are original university-exam-style and PYQ-style practice questions, not verified previous-year questions from a named university.

2 Marks / Short Answer

Q1. Define linear search.

Linear search is a searching method that compares the target with elements sequentially, stopping when a match is found or the collection ends.

Q2. What is the worst-case time complexity?

O(n), because the algorithm may have to check all n elements if the key is absent or at the last position.

Q3. Does linear search need sorted data?

No. It works on both sorted and unsorted collections.

Q4. What is its auxiliary space complexity?

The iterative algorithm uses O(1) auxiliary space, because it stores only a few fixed-size variables.

5 Marks / Worked Explanation

Q5. Explain linear search with a suitable example.

Linear search starts at index 0 and compares each value with the target. For [11, 24, 7, 32], search 7: compare 11 (no), 24 (no), 7 (yes). The output is index 2 after 3 comparisons. If the key is absent, return -1 after checking all entries. The algorithm uses O(n) worst-case time.

Q6. Explain best, average and worst-case time.

Best case: first value matches, one comparison, Θ(1). Average successful case under uniformly likely target positions: (n + 1)/2 comparisons, Θ(n). Worst case: last value or missing target, n comparisons, Θ(n). This explains why linear search is called a linear-time searching method.

Q7. What happens when duplicates exist?

A standard first-match implementation returns the earliest matching index. To find the last match or count all matches, continue scanning through the entire list while remembering matching positions or a count.

10 Marks / Long Answer

Q8. Explain linear search algorithm, C program, flowchart and time-space complexity.

Start with the definition: sequential searching checks array elements from left to right until a match occurs or the data ends. Draw an indexed array. Write the six steps from Section 3 and the flowchart from Section 4. Add the complete C program from Section 9. Explain three cases: one comparison in best case, average (n + 1)/2 for a uniformly placed successful target, and n checks in worst case. State that iterative auxiliary space is O(1). Finish with merits (simple, unsorted input allowed) and limitation (slow on large inputs).

Q9. Differentiate linear and binary search with complexities.

Linear search compares consecutive elements, works on unsorted data and takes O(n) worst-case time. Binary search requires sorted data, tests the middle and discards half the remaining range on each iteration; its worst-case time is O(log n) on an indexed array. Both iterative versions use O(1) auxiliary space. Binary search is preferable for repeated lookups in large already sorted arrays, while linear search is simpler for small or unsorted collections.

16 / Final revision station

Linear Search MCQs, FAQs and Quick Revision

Practice MCQs with Answers

  1. Linear search is also called? A. Binary B. Sequential C. Hash D. Jump. Answer: B — elements are checked sequentially.
  2. Best-case time of first-match linear search? A. O(n) B. O(log n) C. O(1) D. O(n²). Answer: C — first element matches.
  3. Worst case when key is absent? A. 0 B. 1 C. n D. log n comparisons. Answer: C — all n elements are checked.
  4. Sorted array required? A. Yes B. No. Answer: B — any order is allowed.
  5. What does -1 mean in the C programs? A. First value B. Invalid index/not found C. Last value D. Second position. Answer: B.
  6. First matching index in [5, 8, 5, 2] for 5? A. 0 B. 1 C. 2 D. 3. Answer: A — search stops at index 0.
  7. Successful average comparisons for n = 9 (uniform position)? A. 9 B. 5 C. 1 D. 3. Answer: B — (9 + 1)/2 = 5.
  8. Iterative auxiliary space? A. O(n) B. O(log n) C. O(1) D. O(n²). Answer: C.

Frequently Asked Questions

What is linear search in data structure in simple words?

It means checking elements one by one until you locate the target or reach the end. No sorting is necessary.

What is the linear search time complexity?

Best case O(1), successful uniform-position average O(n), and worst case O(n). With an empty array, no key comparison is needed.

What is the difference between linear search and sequential search?

They are two names for the same basic scanning method.

Can linear search find repeated numbers?

Yes. Standard first-match code returns the first index. To count duplicates or print all indices, continue scanning instead of returning early.

What is sentinel linear search?

It temporarily places the target at a final array position so the inner scanning loop needs fewer bounds checks. It must restore the original data, and worst-case time stays O(n).

Can linear search be used on a linked list?

Yes. Start at head, compare each node's data and follow next pointers until a match appears or the pointer becomes NULL.

Is linear search better than binary search?

For small or unsorted data it is often simpler. For large already sorted indexed arrays, binary search uses O(log n) worst-case comparisons rather than O(n). Sorting just for a single search has an additional cost.

Fast viva recap

Names: linear/sequential search. Data: sorted or unsorted. Output: index or -1. First-match code stops immediately on equality.

Complexity recap

Best = O(1). Average = O(n). Worst = O(n). Iterative auxiliary space = O(1). All-occurrence scan = Θ(n).

Chapter 37 / Completed

Conclusion: Search One Step at a Time

Linear search is often the first searching algorithm students learn because the idea is so natural: look at an element, compare it with the target and move forward if needed. It can search unsorted arrays and linked lists without complicated preparation.

For semester exams, practise the index-based dry run, write a complete C program without looking at the answer, and explain why the best case is O(1) but the average and worst cases are O(n). That understanding will also make more advanced searching algorithms easier.

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