Computer Science, asked by vijay01051971, 3 months ago

Linear searching program in java​

Answers

Answered by sharmayachna95
1

Answer:

Linear Search in Java

Linear search is used to search a key element from multiple elements. Linear search is less used today because it is slower than binary search and hashing.

Algorithm:

Step 1: Traverse the array

Step 2: Match the key element with array element

Step 3: If key element is found, return the index position of the array element

Step 4: If key element is not found, return -1

Let's see an example of linear search in java where we are going to search an element sequentially from an array.

public class LinearSearchExample{

public static int linearSearch(int[] arr, int key){

for(int i=0;i<arr.length;i++){

if(arr[i] == key){

return i;

}

}

return -1;

}

public static void main(String a[]){

int[] a1= {10,20,30,50,70,90};

int key = 50;

System.out.println(key+" is found at index: "+linearSearch(a1, key));

}

}

Test it Now

Output:

50 is found at index: 3

Linear Search in Java (Another way)

You can also use a method where array is not predefined. Here, user has to put the elements as input and select one element to check its location.

Similar questions