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.
14 ✕ 28 ✕ 9 ✕ 42 ✓ — Target at index 3.
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
- Definition and terminology
- Working diagram and comparisons
- Algorithm and pseudocode
- Flowchart
- Successful and unsuccessful dry runs
- Time complexity derivation
- Space complexity and extra cases
- Interactive linear search lab
- C program: user input
- C program: duplicate values
- C program: sentinel search
- C program: linked list
- Linear vs binary and use cases
- Common mistakes
- Solved 2/5/10-mark questions
- MCQs, FAQs and revision
What Is Linear Search in Data Structure?

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.
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.
- Compare a[0] = 14 with 42 → not equal.
- Compare a[1] = 28 with 42 → not equal.
- Compare a[2] = 9 with 42 → not equal.
- Compare a[3] = 42 with 42 → found; stop.
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.
- Start and read array A, length n and search key.
- Set index i = 0.
- Compare A[i] with key while i < n.
- If equal, return i immediately.
- Otherwise increase i by 1 and repeat.
- If the loop finishes, return -1 (not found).
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.
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.
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.
Linear Search Dry Run: Found, Not Found and Duplicates
Example A: Successful Linear Search for 42
| Comparison | i (index) | A[i] | A[i] == 42? | Action |
|---|---|---|---|---|
| 1 | 0 | 14 | No | Continue |
| 2 | 1 | 28 | No | Continue |
| 3 | 2 | 9 | No | Continue |
| 4 | 3 | 42 | Yes | Return 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.
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.
| Case | When? | Comparisons | Complexity |
|---|---|---|---|
| Best | First element matches | 1 for n > 0 | Θ(1), O(1) |
| Average (successful, uniform) | Target equally likely at each index | (n + 1) / 2 | Θ(n), O(n) |
| Worst | Last element matches or key absent | n | Θ(n), O(n) |
| Empty array | n = 0 | 0 | Θ(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:
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).
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.
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 comparisonsReady. Press Start, then Next comparison.
Purple = currently examined; gray = checked; gold = matching element. The simulator teaches linear search, not binary search.
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.
#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;
}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.
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.
#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;
}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).
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.
#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;
}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.
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.
#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;
}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.
Linear Search vs Binary Search and Practical Applications
| Feature | Linear Search | Binary Search |
|---|---|---|
| Data order | Sorted or unsorted | Must already be sorted |
| Strategy | Scan elements one by one | Halve the remaining interval |
| Worst-case time | O(n) | O(log n) on an indexed array |
| Best-case time | O(1) | O(1) |
| Iterative extra space | O(1) | O(1) |
| Good for | Small/unsorted data; linked traversal | Large 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.
Common Mistakes in Linear Search Programs
- Off-by-one error: For an array of n elements, valid indices are 0 to n - 1; use
i < n, noti <= n. - Index versus position: If a function returns index 3, that is fourth position when counting from 1.
- 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.
- Duplicates: A return inside the loop gives the first match; counting all matches requires scanning the whole array.
- Missing input validation: Check
scanf()results and the maximum array length before reading input. - Confusing input storage with extra space: An O(n)-size input array does not make the iterative algorithm's auxiliary space O(n).
- Assuming sorting is necessary: Plain sequential search works equally well with an unsorted array.
- Unsafe sentinel logic: Do not forget to restore the overwritten last value and check for n = 0.
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.
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.
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.
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.
Linear Search MCQs, FAQs and Quick Revision
Practice MCQs with Answers
- Linear search is also called? A. Binary B. Sequential C. Hash D. Jump. Answer: B — elements are checked sequentially.
- 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.
- Worst case when key is absent? A. 0 B. 1 C. n D. log n comparisons. Answer: C — all n elements are checked.
- Sorted array required? A. Yes B. No. Answer: B — any order is allowed.
- What does -1 mean in the C programs? A. First value B. Invalid index/not found C. Last value D. Second position. Answer: B.
- 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.
- Successful average comparisons for n = 9 (uniform position)? A. 9 B. 5 C. 1 D. 3. Answer: B — (9 + 1)/2 = 5.
- 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).
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.
