Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Linear Search in Python Program
Linear search is a simple searching algorithm that checks each element in a list sequentially until the target element is found or the entire list is traversed. It's the most straightforward search method but not the most efficient for large datasets.
Algorithm
Start from the leftmost element of the given array and compare the target element x with each element one by one
If x matches with any element, return its index position
If x doesn't match with any elements in the array, return -1 or "element not found"
Visual Representation
Here's how linear search works step by step ?
Implementation
Here's the basic linear search implementation ?
def linearsearch(arr, x):
for i in range(len(arr)):
if arr[i] == x:
return i
return -1
# Example usage
arr = ['t', 'u', 't', 'o', 'r', 'i', 'a', 'l']
x = 'a'
result = linearsearch(arr, x)
if result != -1:
print(f"Element '{x}' found at index {result}")
else:
print(f"Element '{x}' not found in the array")
Element 'a' found at index 6
Example with Numbers
def linearsearch(arr, x):
for i in range(len(arr)):
if arr[i] == x:
return i
return -1
# Searching in a numeric array
numbers = [10, 20, 30, 40, 50]
target = 30
result = linearsearch(numbers, target)
print(f"Number {target} found at index: {result}")
# Searching for a non-existent element
target_missing = 99
result_missing = linearsearch(numbers, target_missing)
if result_missing == -1:
print(f"Number {target_missing} not found in the array")
Number 30 found at index: 2 Number 99 not found in the array
Time and Space Complexity
| Complexity | Best Case | Average Case | Worst Case |
|---|---|---|---|
| Time | O(1) | O(n) | O(n) |
| Space | O(1) | ||
When to Use Linear Search
Linear search is ideal for:
Small datasets - When the array size is small
Unsorted data - When the array is not sorted
Simple implementation - When you need a quick, straightforward solution
One-time searches - When sorting overhead isn't justified
Conclusion
Linear search is a fundamental searching algorithm that works by checking each element sequentially. While it has O(n) time complexity, it's simple to implement and works on both sorted and unsorted arrays, making it suitable for small datasets or when simplicity is preferred over efficiency.
