Here, We discuss about Linear Search, their implementation in C, time and space complexity and its applications.
What is Linear Search?
Linear Search is the simplest searching algorithm. It searches for an element in the list in sequential order.
Linear search is used on a collection of items. We start at one end and check every element until the desired element is not found.
Implementation
Sample Code in C :
//Linear Search in C
#include<stdio.h>
int linearsearch(int arr[], int n, int x)
{
//going through array sequencially
for(int i=0; i<n; i++)
if(arr[i] == x)
return i;
return -1;
}
int main()
{
int data[] = {3, 15, 8, 1, 38, -2, 7};
int x = 1;
int n = sizeof(data) / sizeof(data[0]);
int result = linearsearch(arr, n, x);
if (result == -1)
printf("Element not found");
else
printf("Element found at index : %d", result);
}
Code language: C/AL (cal)
Time and Space Complexity
Time Complexity | |
Worst Case | O(n) |
Best Case | O(1) |
Average Case | O(n) |
Space Complexity | |
Worst Case | O(1) |
Applications
- For searching operations in smaller arrays (<100 items).
Related:
Want to Contribute:-
If you like “To The Innovation” and want to contribute, you can mail your articles to 📧 contribute@totheinnovation.com. See your articles on the main page and help other coders.😎