Linear Search Algorithm
What is Linear Search ?
Linear Search is a searching algorithm which is used to search element in a data set. It is also known as sequential search. It is a method for finding a specific value in a list or array of elements by sequentially checking each element until a match is found or until the end of the list is reached.
In linear search, the elements in the list are not required to be in any particular order. The search starts at the beginning of the list and iterates through each element until the desired value is found. If the value is not found, the search will terminate when the end of the list is reached.
Linear search code:
Python:
def linear_search(arr, x):
for i in range(len(arr)):
if arr[i] == x:
return i
return -1
C++ :
int linearSearch(int arr[],int n, int x) {
for (int i = 0; i < ; i++) {
if (arr[i] == x) {
return i; // Return the index if element found
}
}
return -1; // Return -1 if element not found
}
Java :
public class LinearSearch {
public static int linearSearch(int[] arr, int x) {
int n = arr.length;
for (int i = 0; i < n; i++) {
if (arr[i] == x) {
return i; // Return the index if element found
}
}
return -1; // Return -1 if element not found
}
The linear_search
function takes an array arr
and a value x
as input parameters. It then iterates through each element in the array using a for
loop, checking if the current element is equal to the value x
. If a match is found, the index of the element is returned. If the end of the array is reached without finding the value, the function returns -1
to indicate that the value was not found.
Drawback of Linear Search Algorithm:
While linear search is a simple and easy-to-implement algorithm, it is not the most efficient for large datasets. In the worst case, where the desired value is not in the list or is at the end of the list, the algorithm must iterate through every element of the list, resulting in a time complexity of O(n), where n is the size of the list.
In contrast, other searching algorithms like binary search and hash tables can achieve a faster search time for larger datasets by taking advantage of the ordered or hashed structure of the data. However, linear search remains useful for small lists or as a basic building block for more complex algorithms.
Conclusion :
In conclusion, linear search is a simple and basic algorithm for finding a specific value in an unsorted list or array. Although it is not the most efficient algorithm for large datasets, it is easy to understand and implement, making it a valuable tool for beginners and for simple applications.
Contact me :
If you want you can contact me on:kaushikyash533@gmail.com.