Linear Search Algorithm
Linear Search Algorithm
The algorithm for linear search can be broken down into the following
steps:
If no element is found equal to the key, the search yields “No match
found”.
For example: Consider the array arr[] = {10, 50, 30, 70, 80, 20, 90,
40} and key = 30
Step 1: Start from the first element (index 0) and compare key with each
element (arr[i]).
Comparing key with first element arr[0]. SInce not equal, the
iterator moves to the next element as a potential match.
Comparing key with next element arr[1]. SInce not equal, the
iterator moves to the next element as a potential match.
Figure : Compare key with arr[1]
Step 2: Now when comparing arr[2] with key, the value matches. So the
Linear Search Algorithm will yield a successful message and return the
index of the element when key is found (here 2).
In Linear Search, we iterate over all the elements of the array and check if
it the current element is equal to the target element. If we find any
element to be equal to the target element, then return the index of the
current element. Otherwise, if no element is equal to the target element,
then return -1 as the element is not found.
C++CJavaPythonC#JavaScriptPHP
import java.io.*;
class GFG {
public static int search(int arr[], int N, int x)
if (arr[i] == x)
return i;
return -1;
// Driver code
int x = 10;
// Function call
if (result == -1)
System.out.print(
else
+ result);
Output