How to search array in java

0

 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 inn that case return -1


Java Code :



class HindiCodingCommunity{

public static int search(int[] arr,int num){
for(int i=0;i<arr.length;i++){
if(arr[i]==num){
return i;
}
}
return -1;
}
public static void main(String args[])
{
int arr[] = new int[6];
for(int i=0;i<arr.length;i++){
arr[i]=i+1;
}
int num = 6;

System.out.println(search(arr,num));
}
}



Time Complexity : O(n)

Space Complexity : O(1)


If you want to write for us then please contact us at hindicodingcommunity@gmail.com




Post a Comment

0Comments
Post a Comment (0)

#buttons=(Accept !) #days=(20)

Our website uses cookies to enhance your experience. Learn More
Accept !