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 Below program shows that how to implement this algorithm in Java. Program for Linear Search in Java
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33
|
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
Read more