Linear search is one of the simplest searching algorithms used in computer science. It involves searching through each element in a list or array one by one to find the desired value. While easy to understand and implement, linear search may not be the most efficient method for large datasets. However, its simplicity makes it a great starting point for learning about searching algorithms.
The algorithm works by sequentially checking each element of an array or list, comparing it with the target value. If a match is found, the index of that element is returned. If no match is found after traversing the entire array, the algorithm returns a special value (usually -1
), indicating that the target is not in the list.
-1
.Linear search is suitable when:
However, for large datasets, linear search may be inefficient due to its time complexity of O(n), meaning that it needs to check each element one by one.
Let’s dive deeper into implementing linear search in different languages to understand how it works practically.
def linear_search(arr, target):
for index in range(len(arr)):
if arr[index] == target:
return index # Return the index where the element is found
return -1 # Return -1 if the element is not found
# Sample usage
arr = [3, 9, 15, 8, 23, 74, 18]
target = 8
result = linear_search(arr, target)
if result != -1:
print(f"Element found at index {result}")
else:
print("Element not found")
Python makes it easy to implement linear search due to its concise syntax. In this code, the function linear_search
returns the index of the first occurrence of target
in the array.
function linearSearch(arr, target) {
for (let i = 0; i < arr.length; i++) {
if (arr[i] === target) {
return i; // Return index if target is found
}
}
return -1; // Return -1 if target is not found
}
// Sample usage
const arr = [3, 9, 15, 8, 23, 74, 18];
const target = 8;
const result = linearSearch(arr, target);
if (result !== -1) {
console.log(`Element found at index ${result}`);
} else {
console.log("Element not found");
}
The JavaScript implementation is nearly identical to the Python version. It iterates through the array, comparing each element to the target, and returns the index of the first match.
#include <iostream>
using namespace std;
int linearSearch(int arr[], int size, int target) {
for (int i = 0; i < size; i++) {
if (arr[i] == target) {
return i; // Return the index where the element is found
}
}
return -1; // Return -1 if the element is not found
}
int main() {
int arr[] = {3, 9, 15, 8, 23, 74, 18};
int target = 8;
int size = sizeof(arr) / sizeof(arr[0]);
int result = linearSearch(arr, size, target);
if (result != -1) {
cout << "Element found at index " << result << endl;
} else {
cout << "Element not found" << endl;
}
return 0;
}
In C++, the implementation involves checking each element in the array until the target is found. If the target is not found, it returns -1
.
Linear search has a time complexity of O(n), where n
is the number of elements in the list. This means that in the worst-case scenario, the algorithm will have to check every single element in the array.
Linear search may not be the fastest algorithm, but it still plays an essential role in various real-world applications:
Early Exit Optimization: Instead of always iterating through the entire list, you can exit the loop as soon as the target is found. This saves time in best-case scenarios.
Bidirectional Linear Search: This variation starts from both ends of the array and moves toward the middle. This can sometimes reduce the search time when the target is closer to the middle.
Sentinel Linear Search: In this optimization, instead of checking for the end of the array, a special value called a sentinel is placed at the last position. This eliminates the need to check for the end condition in each iteration, which can save time.
Example of Sentinel Linear Search in Python:
def sentinel_linear_search(arr, target):
n = len(arr)
last = arr[n - 1]
arr[n - 1] = target # Set the sentinel value to the target
i = 0
while arr[i] != target:
i += 1
arr[n - 1] = last # Restore the last element
return i if i < n - 1 else -1