The preceding Java code implements linear search.
- import java.util.Scanner;
- class LinearSearch
- {
- public static void main(String args[])
- {
- int count, num, element, array[];
-
- Scanner input = new Scanner(System. in );
- System.out.println("Enter number of elements in array:");
- num = input.nextInt();
-
- array = new int[num];
- System.out.println("Enter " + num + " integers:");
-
- for (count = 0; count < num; count++)
- array[count] = input.nextInt();
- System.out.println("Enter the element to be searched:");
- element = input.nextInt();
- for (count = 0; count < num; count++)
- {
- if (array[count] == element)
- {
- System.out.println(element + " is present at location " + (count + 1));
-
-
- break;
- }
- }
- if (count == num)
- System.out.println(element + " doesn't exist in array :(");
- }
- }
Thank you, keep learning and sharing