What Is Linear Search?
Table of contents
Linear Search is searching from the first element till you find the element that you are looking for. If no value is found return -1 For Example arr = [2,5,10,15,-19,35,8,-6,17] and the target element is 35 which is present in the 5th index. So you need to check the first index i.e. arr[0] and compare it with the target element, if it matches it will return the index value of the target element. If not found go for the second index i.e. arr[1] and so on till you find which index number matches the target element.
Time Complexity Of Linear Search
Best case : 0(1) It's when we start looking for the target element and find it in the first index, eliminating the need to look at other components. Let's say you have a 1 lakh-element array, and the target element is in the first index, which means it will only have to make one comparison.
Worst case : 0(N) N = Size of array In the worst-case scenario, it will continue to examine all of the elements in the specified array until the target element is found. Now, let's take the same array with 1 lakh items, and if the target element isn't discovered, It will have to perform 1 lakh comparisons.
Code For Linear Search
public class Main { public static void main(String[] args) { int[] nums = {23, 45, 1, 2, 8, 19, -3, 16, -11, 28}; int target = 19; boolean ans = linearSearch(nums, target); System.out.println(ans); }
// search the target
static int linearSearch(int[] arr, int target)
{
if (arr.length == 0)
{
return -1;
}
// run a for loop
for (int index = 0 ; index<arr.length ; index++ ){
//check for element at every index if it is equals to target element
int element = arr[index]
if (element == arr[index])
{
return index;
}
}
// this line will execute if none of the return statements above has executed
// hence the target was not found
return -1;
}