Java – Linear Search

Previous
Next

Linear Search:

  • Searching algorithm to check whether the element is present or not in the array.
  • In linear search, index element always compare with the element to be searched.
  • If element found, it returns the index as location.
  • If element not found, it returns an error message.
import java.util.Scanner;
class Main
{
	static int arr[ ];
	static boolean found=false;
	public static void main(String[] args) 
	{
		Scanner scan = new Scanner(System.in);
		System.out.print("Enter array size : ");
		int n = scan.nextInt();
		arr = new int[n];

		System.out.println("Enter "+n+" elements : ");
		for (int i=0 ; i<n ; i++)
		{
			arr[i] = scan.nextInt();
		}

		System.out.print("Enter element to be searched : ");
		int key = scan.nextInt();

		for (int i=0 ; i<n ; i++)
		{
			if(key == arr[i])
			{
				System.out.println("Element " + key + " found at location : " + i);
				found = true;
				break;
			}
		}
		if(!found)
			System.out.println("Element not found");
	}
}
Previous
Next

Add Comment

Courses Enquiry Form