In this article we will discuss linear search in java. Searching is an operation in the array through which we find whether an element is present in the array or not. If the element is present in the array then we return the index of that number and if the number is not present in the array in that case we return -1 as output . So lets take an example and see how things goes.
Input : [ 1, 2, 3, 4, 5, 6] , number : 6
Outut : 5
Input : [ 1, 2, 3, 4, 5, 6] , number : 55
Outut : -1
nput : [ 1] , number : 6
Outut : -1
Steps:
1. We are given an array and a number.
2. First we run a for loop over array elements
i. We take i=0 and compare if ith element is equal to the given number.
ii. If ith number is equal to that given number then return i
iii. Else move to the next element
3. If no ith element is equal to given number then in that case return -1
CPP Code :
Time Complexity : O(n)
Space Complexity : O(1)
If you want to write for us then please contact us at hindicodingcommunity@gmail.com