forked from Ayush7-BYTE/DSA
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathLinearSearch.java
More file actions
29 lines (25 loc) · 774 Bytes
/
LinearSearch.java
File metadata and controls
29 lines (25 loc) · 774 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
class LinearSearch {
// This function returns index of element x in arr[]
static int search(int arr[], int n, int x)
{
for (int i = 0; i < n; i++) {
// Return the index of the element if the element
// is found
if (arr[i] == x)
return i;
}
// return -1 if the element is not found
return -1;
}
public static void main(String[] args)
{
int[] arr = { 3, 4, 1, 7, 5,6,9};
int n = arr.length;
int x = 4;
int index = search(arr, n, x);
if (index == -1)
System.out.println("Element is not present in the array");
else
System.out.println("Element found at position " + index);
}
}