Introduction to Linear Search Algorithm: Time Complexity and Examples for 2025
Updated on Feb 12, 2025 | 14 min read | 7.9k views
Share:
For working professionals
For fresh graduates
More
Updated on Feb 12, 2025 | 14 min read | 7.9k views
Share:
Table of Contents
Linear search scans each element sequentially to find a target value. While basic, it remains relevant in 2025 for small datasets, unsorted lists, and real-time applications where advanced algorithms aren’t necessary.
Read on to explore its workings, real-world applications, and how to implement it in C and Python.
A linear search algorithm searches each element in a dataset sequentially until the target is found or the end is reached. Its simplicity makes it useful for real-time applications like IoT device management and sensor monitoring.
For example, in a smart home system, linear search can efficiently scan through connected device logs to identify anomalies or locate specific device statuses without the overhead of sorting data.
Understanding the mechanics of linear search is crucial for identifying when it’s the most efficient option. Let’s break down each step to clarify how this straightforward method ensures reliable results.
The linear search algorithm follows a straightforward process:
Also Read: Sorting in Data Structure: Categories & Types [With Examples]
Though simple, linear search’s efficiency depends on the size of the dataset. Its O(n) time complexity means that as data grows, performance decreases linearly, making it less suitable for large datasets.
However, the constant O(1) space complexity ensures minimal memory usage, which is critical in low-power devices and embedded systems in 2025.
Let’s dive into performance metrics and explore scenarios where linear search remains an optimal choice despite its linear time cost.
1. Time Complexity:
2. Space Complexity:
Why This Matters in 2025: In low-power devices or embedded systems, where memory is constrained, linear search’s minimal space requirements make it an optimal choice for basic search tasks.
Also Read: Time and Space Complexity in Machine Learning Explained
Examples are key to grasping the real-world applicability of linear search. Imagine scanning an unsorted contact list on your smartphone for a specific name or searching through unstructured data logs in cybersecurity applications.
These practical examples will help solidify how the algorithm works and why it’s still relevant in day-to-day programming and industry-specific scenarios in 2025.
Let’s use an example to understand these steps:
Input:
Process:
Output: Key found at Index 2
Explanation: The algorithm starts from index 0 and checks each element in the list. When it reaches index 2, the value 30 matches the target value (key), and it stops. It then returns the index (2) where the element was found.
Now, let’s follow these steps for searching a student’s ID in an unsorted list of student IDs:
Array: [1023, 1045, 1078, 1099, 1134]
Target ID: 1078
Step-by-Step Search:
In this example, the linear search found the target after three comparisons.
Also Read: Linear Data Structure: Types, Characteristics, Applications, and Best Practices
The linear search algorithm doesn’t rely on the data being sorted and can be applied to various data structures, from arrays and linked lists to text files.
In an age where complex algorithms dominate, linear search’s predictability and ease of implementation make it a go-to solution in situations where speed of development and resource constraints are factors.
Let’s unpack these features and why they matter today:
Also Read: Difference Between Linear and Non-Linear Data Structures
In 2025, as real-time data processing becomes more prevalent, linear search offers a fast, reliable solution where other algorithms might be overkill. Let’s get into when linear search is the most effective tool in your programming toolkit.
Also Read: Top 30+ DSA Projects with Source Code for 2025: From Beginner to Advanced
Now that you’ve grasped the introduction to linear search algorithm, let’s look at the real-world implementations of linear search in C, Python, Java, and data structures.
Linear search is widely used in programming for quick and simple search operations. It is especially useful when dealing with small datasets, unsorted data, or real-time scenarios where complex preprocessing isn't feasible.
Below are four practical examples of linear search, each demonstrating its use in different programming languages and data structures.
C is often used in low-level system programming. Unlike higher-level languages, C allows direct memory access and optimized performance for tasks like linear search. Here’s an example of a linear search program in C, where we search for an integer in an array.
Problem Statement: Given an array of integers, find the index of a target value using the linear search algorithm.
Code:
#include <stdio.h>
// Function to perform linear search
int linearSearch(int arr[], int size, int target) {
for (int i = 0; i < size; i++) {
if (arr[i] == target) { // Check if the element matches the target
return i; // Return index if found
}
}
return -1; // Return -1 if not found
}
int main() {
int arr[] = {10, 20, 30, 40, 50}; // Sample array
int target = 30; // Element to search for
int size = sizeof(arr) / sizeof(arr[0]); // Calculate array size
int result = linearSearch(arr, size, target);
if (result != -1) {
printf("Element found at index %d\n", result);
} else {
printf("Element not found\n");
}
return 0;
}
Output:
Element found at index 2
Real-World Use Case: Linear search program in C is commonly used in embedded systems where searching small datasets, like IoT sensor logs, needs a lightweight and quick solution.
Also Read: Top 25+ C Programming Projects for Beginners and Professionals
Python is widely used for data analysis, automation, and AI. A linear search in Python can be implemented efficiently using simple loops.
Problem Statement: Find the position of a target element in a list.
Code:
def linear_search(arr, target):
for i in range(len(arr)):
if arr[i] == target:
return i # Return the index if found
return -1 # Return -1 if not found
# Example usage
arr = [5, 8, 12, 25, 35]
target = 25
result = linear_search(arr, target)
if result != -1:
print(f"Element found at index {result}")
else:
print("Element not found")
Output:
Element found at index 3
Real-World Use Case: Python’s simplicity makes it a popular choice in data science and automation. A customer support chatbot could use a linear search in Python to check if a user query matches predefined responses stored in a list.
Also Read: Top 50 Python Project Ideas with Source Code in 2025
Java is a high-performance, object-oriented language widely used in enterprise applications and mobile development.
Problem Statement: Implement a linear search algorithm in Java to find a target number in an array.
Code:
public class LinearSearch {
public static int linearSearch(int[] arr, int target) {
for (int i = 0; i < arr.length; i++) {
if (arr[i] == target) {
return i; // Return the index if found
}
}
return -1; // Return -1 if not found
}
public static void main(String[] args) {
int[] arr = {3, 7, 15, 23, 42};
int target = 23;
int result = linearSearch(arr, target);
if (result != -1) {
System.out.println("Element found at index " + result);
} else {
System.out.println("Element not found");
}
}
}
Output:
Element found at index 3
Real-World Use Case: Linear search in Java is useful for small datasets or cases where indexing isn't feasible.
Also Read: 45+ Java project ideas for beginners in 2025 (With Source Code)
Unlike arrays, where direct indexing enables quick access, linked lists require scanning from the head node, making linear search the only feasible option for unordered lists.
This method is also applied in other sequential data structures, such as queues and unordered sets, where direct access is not possible. However, its efficiency depends on the structure’s size, as the worst-case time complexity remains O(n) in all cases.
Problem Statement: Implement a linear search in a singly linked list.
Code (Python Example):
class Node:
def __init__(self, data):
self.data = data
self.next = None
class LinkedList:
def __init__(self):
self.head = None
def append(self, data):
new_node = Node(data)
if not self.head:
self.head = new_node
return
temp = self.head
while temp.next:
temp = temp.next
temp.next = new_node
def linear_search(self, target):
current = self.head
index = 0
while current:
if current.data == target:
return index
current = current.next
index += 1
return -1
# Example usage
ll = LinkedList()
ll.append(10)
ll.append(20)
ll.append(30)
target = 20
result = ll.linear_search(target)
if result != -1:
print(f"Element found at index {result}")
else:
print("Element not found")
Output:
Element found at index 1
Real-World Use Case: Linear search in Python in linked lists is useful for memory-efficient applications, such as blockchain transactions, where data is stored in a linked structure and quick lookups are required.
Also Read: 12 Amazing Real-World Applications of Python
While linear search is effective for small datasets, binary search offers a faster alternative for sorted data. Let’s explore its process, features, and when to use it.
upGrad’s Exclusive Data Science Webinar for you –
How upGrad helps for your Data Science Career?
Binary Search is an efficient search algorithm used to find an element in a sorted array by repeatedly dividing the search space in half.
Unlike linear search, which checks elements sequentially, binary search significantly reduces search time by eliminating half of the dataset with each comparison. This makes it ideal for large datasets where speed is crucial.
Binary Search follows a divide-and-conquer approach:
1. Start with a sorted array.
2. Identify the middle element.
3. Compare the middle element with the target:
4. Repeat the process recursively or using a loop until the target is found or the search range is empty.
Here are some key features of binary search:
Let’s understand this better with a binary search algorithm:
Example Problem: Find the target number 40 in a sorted array using binary search.
Code:
def binary_search(arr, target):
left, right = 0, len(arr) - 1 # Define the search range
while left <= right:
mid = left + (right - left) // 2 # Find the middle index
if arr[mid] == target:
return mid # Target found, return index
elif arr[mid] < target:
left = mid + 1 # Search in the right half
else:
right = mid - 1 # Search in the left half
return -1 # Target not found
# Example usage
arr = [10, 20, 30, 40, 50, 60, 70]
target = 40
result = binary_search(arr, target)
if result != -1:
print(f"Element found at index {result}")
else:
print("Element not found")
Output:
Element found at index 3
Explanation:
When to Use Binary Search?
Also Read: Difference Between Linear Search and Binary Search
Now that you've seen binary search in action, how does it compare to linear search? Let’s break down its strengths, limitations, and when it’s the better choice.
With big data and AI-driven search engines dominating, linear search might seem outdated, yet it remains a crucial fallback mechanism in various real-world scenarios. Unlike algorithms optimized for structured databases, linear search excels in dynamic environments where preprocessing or indexing isn't feasible.
However, it has significant limitations that make it inefficient for large-scale applications. Its sequential nature results in poor scalability, making it unsuitable for datasets where faster, indexed retrieval is required.
Understanding both its strengths and limitations is essential for making informed choices in search optimization:
Advantages |
Disadvantages |
Simple to Implement – Easy to write and understand, making it ideal for beginners. | Slow for Large Datasets – Runs in O(n) time, making it inefficient when searching large lists. |
Works on Unsorted Data – No need for prior sorting, unlike binary search. | Inefficient for Sorted Data – Performs unnecessary comparisons even when the data is already sorted. |
Supports Various Data Structures – Can be used with arrays, linked lists, and text files. | Not Scalable – Becomes impractical for datasets with millions of elements. |
Minimal Memory Usage (O(1) Space Complexity) – Requires no extra storage beyond the given dataset. | Sequential Checking – Cannot skip elements, leading to longer search times in large lists. |
Works Well for Small Lists – Efficient for datasets where n is small, making sorting unnecessary. | Not Suitable for Indexed Searches – Cannot take advantage of pre-structured data like hash tables. |
Also Read: Importance of Data Science in 2025 [A Simple Guide]
Mastering search algorithms requires hands-on learning. In the next section, discover how upGrad’s courses can help you build expertise in linear search and beyond.
upGrad, South Asia’s leading Higher EdTech platform offers comprehensive courses that equip over 10M+ learners with highly relevant programming skills, including the in-demand search techniques.
The comprehensive materials include detailed explanations, algorithmic analysis, and practical implementations across different programming languages.
Here are some relevant courses you can check out:
You can also get personalized career counseling with upGrad to guide your career path, or visit your nearest upGrad center and start hands-on training today!
Unlock the power of data with our popular Data Science courses, designed to make you proficient in analytics, machine learning, and big data!
Elevate your career by learning essential Data Science skills such as statistical modeling, big data processing, predictive analytics, and SQL!
Stay informed and inspired with our popular Data Science articles, offering expert insights, trends, and practical tips for aspiring data professionals!
Get Free Consultation
By submitting, I accept the T&C and
Privacy Policy
Start Your Career in Data Science Today
Top Resources