on Leave a Comment

Linear Search in Java

Linear search is a searching technique to search an element in array. We can also search element in array using binary search. Linear search is slower than binary search, so it is less used. But in linear search we don't need to sort an array while performing searching. So both searching technique have their own advantages and disadvantages.

In linear search, we traverse an array for searching specific element. If array is found, we note its index number and if item is not found till end, we display that "Element is not found".

Java program for linear search

/*Linear Search in Java*/
import java.util.Scanner;
public class LinearSearch{
 public static void search(int arr[], int item){
  int i, flag = 0;
  for(i = 0; i<arr.length; i++){
   if(arr[i] == item){
    flag = 1;
    System.out.println("Element "+arr[i]+" is found at index "+i);
   }
  }
  if(flag!=1)
   System.out.println("Element "+arr[i]+" is not found");
 }
 public static void main(String[] args){
  Scanner read = new Scanner(System.in);
  int []arr = new int[5];
  System.out.print("Enter Array Element (5 Elements): ");
  for(int i = 0; i<arr.length; i++){
   arr[i] = read.nextInt();
  }
  System.out.print("Enter the element to search: ");
  int item = read.nextInt();
  search(arr, item);
 }
}

Output:

Enter Array Element (5 Elements): 1 2 3 4 5
Enter the element to search: 3
Element 3 is found at index 2




0 comments:

Post a Comment