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
Now we are seeing the program of linear search..
package com.ritesh;
class search{
public int lin(int search){
int [] arr={12,4,67,77,34,886,55,8654,2}; //defining the array
for(int i=0;i<arr.length;i++){ //loop
if(search==arr[i]){
System.out.println(i+" is found on the array");
return i; // return the value if it is found
}
}
return -1;
}
}
public class linner {
public static void main(String[] args) {
search sc=new search();
System.out.println(sc.lin(4)); //inslized the value to the search
}
}
Comments
Post a Comment