Linear Search in Java
Chapter:
Miscellaneous
Last Updated:
09-07-2016 04:53:58 UTC
Program:
/* ............... START ............... */
import java.util.Scanner;
public class JavaLinearSearch {
public static void main(String args[]) {
int c, n, search, array[];
Scanner in = new Scanner(System.in);
System.out.println("Enter number of elements");
n = in.nextInt();
array = new int[n];
System.out.println("Enter " + n + " integers");
for (c = 0; c < n; c++)
array[c] = in.nextInt();
System.out.println("Enter the number to search");
search = in.nextInt();
for (c = 0; c < n; c++) {
if (array[c] == search) {
System.out.println(search + " is present at " + "location " + (c + 1) + ".");
break;
}
}
if (c == n)
System.out.println(search + " is not present in array.");
}
}
/* ............... END ............... */
Output
Enter number of elements
5
Enter 5 integers
5
6
7
9
10
Enter the number to search
7
7 is present at location 3.
Notes:
-
Linear search is very simple, To check if an element is present in the given list we compare search element with every element in the list.
- In Big O Notation it is O(N). The speed of search grows linearly with the number of items within your collection.
Tags
Linear Search, Java