-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathLinearSearch.java
More file actions
31 lines (28 loc) · 824 Bytes
/
Copy pathLinearSearch.java
File metadata and controls
31 lines (28 loc) · 824 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
public class LinearSearch
{
public static int linearSearch(int[] arr, int key)
{
for (int i = 0; i < arr.length; i++)
{
if (arr[i] == key)
{
return i; // Return the index where the key is found
}
}
return -1; // Return -1 if the key is not found
}
public static void main(String[] args)
{
int[] numbers = {10, 20, 30, 40, 50};
int key = 30; // Element to search for
int result = linearSearch(numbers, key);
if (result != -1)
{
System.out.println("Element " + key + " found at index: " + result);
}
else
{
System.out.println("Element " + key + " not found in the array.");
}
}
}