In this tutorial, you'll study the linear search algorithm. you'll also find functional samples of linear search C programming, C ++, Java, and Python.
Linear search is the simplest search algorithm that searches for an item during a list in sequential order. We start at one end and check each item until the item we would like isn't found.
Otherwise, return not found.
Time complexity: O (n)
Spatial complexity: O (1)
the primary and foremost algorithm that might strike an individual is to iterate through each element of the array and check whether or not it's adequate to the search element (x).
This type of algorithm is known as a Linear Search Algorithm in Data Structure.
Linear search is the simplest search algorithm that searches for an item during a list in sequential order. We start at one end and check each item until the item we would like isn't found.
How does the linear search algorithm work?
- The following steps are followed to seek out a component k = 1 within the list below.
linear search algorithm |
- Start with the primary element, compare k with each element x.
Linear Search in c |
- If x == k, return the index.
linear search |
Linear Search Algorithm
Linear Search Algorithm |
Linear Search Program In C
#include<stdio.h> int search(int array[], int n, int x) { // Going through array sequencially for (int i = 0; i < n; i++) if (array[i] == x) return i; return -1; } int main() { int array[] = {2, 4, 0, 1, 9}; int x = 1; int n = sizeof(array) / sizeof(array[0]); int result = search(array, n, x); (result == -1) ? printf("Element not found") : printf("Element found at index: %d", result); }
Otherwise, return not found.
Complexities For linear search Algorithm
Time complexity: O (n)
Spatial complexity: O (1)
Use Of Linear Search Algorithm
Let's say you would like to look for a component (x) during a given array (arr).the primary and foremost algorithm that might strike an individual is to iterate through each element of the array and check whether or not it's adequate to the search element (x).
This type of algorithm is known as a Linear Search Algorithm in Data Structure.