Difficulty: Easy
Correct Answer: O(n)
Explanation:
Introduction / Context:
Linear search is one of the simplest searching algorithms taught in introductory programming and data structures courses. It is often used on small or unsorted collections of data. Knowing its time complexity is important for analyzing algorithm efficiency and for comparing it with more advanced search methods like binary search.
Given Data / Assumptions:
- We have an unsorted list or array containing n elements.
- We wish to search for a given target value in this list.
- The algorithm used is linear search, which checks elements one by one.
- The question specifically asks for the time complexity in the worst case.
Concept / Approach:
In linear search, we start from the first element and compare it with the target. If it does not match, we move to the next element, and so on, until we either find the target or exhaust the list. In the worst case, the target is either at the last position or not present at all, forcing us to make n comparisons. When expressing algorithmic time complexity, we use Big O notation, which focuses on the highest order term as n becomes large.
Step-by-Step Solution:
Step 1: Let the list contain n elements, indexed from 1 to n.
Step 2: In linear search, the algorithm compares the target with element 1, then element 2, and so on.
Step 3: In the best case, the target is at the first position, and only one comparison is needed.
Step 4: In the worst case, the algorithm must compare the target with all n elements before concluding success or failure.
Step 5: Therefore, the total number of comparisons in the worst case is proportional to n.
Step 6: In Big O notation, a quantity proportional to n is written as O(n).
Verification / Alternative Check:
You can verify this by implementing linear search in code and counting comparisons for different positions of the target. As the list grows from 10 to 100 to 1000 elements, you will observe that the worst case number of comparisons grows roughly linearly with n. No nested loops are involved, so the complexity is not quadratic or logarithmic.
Why Other Options Are Wrong:
Option A (O(n^2)) would imply a nested loop, which linear search does not have.
Option B (O(n log n)) is typical of more complex algorithms like efficient sorting, not a simple search through one list.
Option D (O(log n)) applies to algorithms like binary search on sorted data, which repeatedly halves the search interval. Linear search does not halve the search space; it checks elements sequentially.
Common Pitfalls:
A common mistake is to confuse linear search with binary search or to assume any search can be done in logarithmic time. Time complexity always depends on the structure of the algorithm and the properties of the data, such as whether it is sorted.
Final Answer:
The worst case time complexity of linear search on an unsorted list of size n is O(n).
Discussion & Comments