forked from Haresh1204/Algorithms
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathLinear Search
38 lines (32 loc) · 875 Bytes
/
Linear Search
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
class GFG {
// Function for linear search
public static int search(int arr[], int x)
{
int n = arr.length;
// Traverse array arr[]
for (int i = 0; i < n; i++) {
// If element found then
// return that index
if (arr[i] == x)
return i;
}
return -1;
}
// Driver Code
public static void main(String args[])
{
// Given arr[]
int arr[] = { 2, 3, 4, 10, 40 };
// Element to search
int x = 10;
// Function Call
int result = search(arr, x);
if (result == -1)
System.out.print(
"Element is not present in array");
else
System.out.print("Element is present"
+ " at index "
+ result);
}
}