-
Notifications
You must be signed in to change notification settings - Fork 82
/
LinearSearch.java
42 lines (30 loc) · 1.09 KB
/
LinearSearch.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
34
35
36
37
38
39
40
41
42
import java.util.Scanner;
public class LinearSearch{
public static void main(String[] args) {
int numberOfElements, searchElement, arr[];
Scanner scanner = new Scanner(System.in);
System.out.print("Enter number of elements: ");
numberOfElements = scanner.nextInt();
arr = new int[numberOfElements];
System.out.print("Enter the " + numberOfElements + " elements: ");
for(int i = 0; i < numberOfElements; i++) {
arr[i] = scanner.nextInt();
}
System.out.print("Enter the search value: ");
searchElement = scanner.nextInt();
int index = linearSearch(arr, searchElement);
if(index != -1)
System.out.println(searchElement + " found at index " + index);
else
System.out.println(searchElement + " not found in the array");
scanner.close();
}
public static int linearSearch(int[] arr, int search){
for(int i = 0; i < arr.length; i++){
if(arr[i] == search){
return i;
}
}
return -1;
}
}