Assume that item is in an array in random order and we have to find an item. Then the only way to search for a target item is, to begin with, the first position and compare it to the target. If the item is at the same, we will return the position of the current item. Otherwise, we will move to the next position. If we arrive at the last position of an array and still can not find the target, we return -1. This is called the Linear search or Sequential search.
Below is the code syntax for the linear search.
C++
// Linear Search in C++
#include <iostream>
usingnamespacestd;
intsearch(intarray[], intn, intx)
{
// Going through array sequencially
for(inti = 0; i < n; i++)
if(array[i] == x)
returni;
return-1;
}
C
// Linear Search in C
#include <stdio.h>
intsearch(intarray[], intn, intx)
{
// Going through array sequencially
for(inti = 0; i < n; i++)
if(array[i] == x)
returni;
return-1;
}
Java
/*package whatever //do not write package name here */
importjava.io.*;
classMain {
publicstaticintliner(intarr[], intx)
{
for(inti = 0; i < arr.length; i++) {
if(arr[i] == x)
returni;
}
return-1;
}
}
Python
# Linear Search in Python
deflinearSearch(array, n, x):
fori inrange(0, n):
if(array[i] ==x):
returni
return-1
C#
// Linear Search in c#
usingSystem;
usingSystem.Collections.Generic;
classGFG
{
publicstaticintsearch(int[] array, intn, intx)
{
// Going through array sequencially
for(inti = 0; i < n; i++)
if(array[i] == x)
returni;
return-1;
}
}
// This code is contributed by adityapatil12.
Javascript
<script>
// Linear Search in C++
functionsearch(array, n, x)
{
// Going through array sequencially
for(let i = 0; i < n; i++){
if(array[i] == x){
returni;
}
}
return-1;
}
// The coee is contributed by Gautam goel.
</script>
BINARY SEARCH
In a binary search, however, cut down your search to half as soon as you find the middle of a sorted list. The middle element is looked at to check if it is greater than or less than the value to be searched. Accordingly, a search is done to either half of the given list
We use cookies to ensure you have the best browsing experience on our website. By using our site, you
acknowledge that you have read and understood our
Cookie Policy &
Privacy Policy
Please Login to comment...