-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathLinearSearch.java
70 lines (58 loc) · 1.7 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
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
import java.util.*;
public class LinearSearch {
public int search(int arr[], int element) {
int size = arr.length;
for(int i=0;i<size;i++){
if(arr[i] == element){
return i;
}
}
return -1;
}
public static void main(String[] args) {
Scanner xp = new Scanner(System.in);
LinearSearch obj = new LinearSearch();
System.out.println("Please enter the size of array ");
int size = xp.nextInt();
int arr[] = new int[size];
System.out.println("Please enter the elements of array ");
for(int i=0;i<size;i++){
arr[i] = xp.nextInt();
}
System.out.println("Please enter the element to be searched ");
int element = xp.nextInt();
if(obj.search(arr, element) == -1){
System.out.println("The element is not present in the array");
System.exit(0);
}
int result = obj.search(arr, element);
System.out.println("The element is present at index "+result);
xp.close();
}
}
// Java code for linearly searching x in arr[].
// import java.io.*;
// class GFG {
// public static int search(int arr[], int N, int x)
// {
// for (int i = 0; i < N; i++) {
// if (arr[i] == x)
// return i;
// }
// return -1;
// }
// // Driver code
// public static void main(String args[])
// {
// int arr[] = { 2, 3, 4, 10, 40 };
// int x = 10;
// // Function call
// int result = search(arr, arr.length, x);
// if (result == -1)
// System.out.print(
// "Element is not present in array");
// else
// System.out.print("Element is present at index "
// + result);
// }
// }