forked from ayan-b/Linear-Search
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathLinearSearch.java
More file actions
36 lines (33 loc) · 929 Bytes
/
Copy pathLinearSearch.java
File metadata and controls
36 lines (33 loc) · 929 Bytes
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
import java.util.ArrayList;
import java.util.Scanner;
public class LinearSearch {
public static int lsearch (ArrayList<Integer> numbers, int target) {
int index = 0;
for (int num : numbers) {
if (num == target) {
return index;
}
index++;
}
return -1;
}
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
ArrayList<Integer> numbers = new ArrayList<>();
System.out.println("How many number are you going to enter? ");
int n = scan.nextInt();
System.out.println("Enter the list of numbers: ");
for (int i = 0; i < n; i++) {
int num = scan.nextInt();
numbers.add(num);
}
System.out.println("Enter the target: ");
int target = scan.nextInt();
int foundedIndex = lsearch(numbers, target);
if (foundedIndex > -1)
System.out.println("Element found on index " + foundedIndex);
else
System.out.println("Element not found!");
scan.close();
}
}