Linear Search in Java

Here you will learn about linear search in Java.

It is one of the simplest and basic searching algorithm which is also known as sequential search.

The targeted element is compared with each element of array until it is found. Its best and worst case time complexity is O (1) and O (n) respectively.

Also Read: Binary Search in Java

Linear Search in Java
Image Source

Below program shows that how to implement this algorithm in Java.

Program for Linear Search in Java

import java.util.Scanner;

class LinearSearchJava {
	public static void main(String...s){
		int a[],n,x,i;
		Scanner sc = new Scanner(System.in);
		System.out.println("Enter size of array:");
		
		n = sc.nextInt();
		a = new int[n];
		
		System.out.println("\nEnter array elements:");
		for(i=0;i<n;++i){
			a[i]=sc.nextInt();
		}
		
		System.out.println("\nEnter element to search:");
		x = sc.nextInt();
		
		for(i=0;i<n;++i){
			if(a[i]==x){
				break;
			}
		}
		
		if(i<n){
			System.out.print("\nElement found at postion "+(i+1));
		}
		else{
			System.out.print("\nElement not found");
		}			
	}
}

 

Output

Enter size of array:
5

Enter array elements:
5 7 12 8 4

Enter element to search:
8

Element found at postion 4

2 thoughts on “Linear Search in Java”

  1. I am new to programing can u plz tell me why u have used string…s in main method instead of string[] args…what does it mean??

    1. You can also use String…s instead of String args[]. Actually this feature was added in java 1.5. Both of them do the same work.

Leave a Comment

Your email address will not be published. Required fields are marked *