-
Notifications
You must be signed in to change notification settings - Fork 0
/
LinearSearch.java
44 lines (37 loc) · 1.26 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
43
44
import java.util.Scanner;
/**
* This is an implementation of the linear search algorithm.
* @author @inforkgodara
*
*/
public class LinearSearch {
/**
* Linear search implementation.
* @param list the array to be searched.
* @param search the element being looked for in the array.
* @return the index at which the search element was first found or -1 if not found.
*/
public static int search(int[] list, int search) {
int length = list.length;
for (int index = 0; index < length; index++) {
if (list[index] == search) {
return index;
}
}
return -1;
}
public static void main(String[] args) {
System.out.print("Enter length of list : ");
Scanner scanner = new Scanner(System.in);
int length = scanner.nextInt();
int[] list = new int[length];
for (int index = 0; index < length; index++) {
list[index] = scanner.nextInt();
}
System.out.print("Enter element to search : ");
int search = scanner.nextInt();
int elementAt = search(list, search);
String result = elementAt == -1 ? "Element not found." : "Element is at index " + elementAt;
System.out.println(result);
}
}