-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathDSA-lab6(a)-Linear_Search
More file actions
62 lines (49 loc) · 1.55 KB
/
DSA-lab6(a)-Linear_Search
File metadata and controls
62 lines (49 loc) · 1.55 KB
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
import java.util.Scanner;
/**
* LinearSearch Program
* ---------------------
* This program searches for an element in an array using Linear Search.
*
* Time Complexity:
* - Best Case: O(1)
* - Worst Case: O(n)
*/
public class LinearSearch {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
// Taking input from user
System.out.print("Enter number of elements: ");
int n = sc.nextInt();
int[] arr = new int[n];
System.out.println("Enter elements:");
for (int i = 0; i < n; i++) {
arr[i] = sc.nextInt(); // storing input values
}
// Taking element to search
System.out.print("Enter element to search: ");
int key = sc.nextInt();
// Calling linear search function
int pos = linearSearch(arr, key);
// Displaying result
if (pos == -1) {
System.out.println("Element not found");
} else {
System.out.println("Element found at position: " + (pos + 1));
}
sc.close(); // closing scanner
}
/**
* Linear Search Algorithm
* Checks each element one by one until match is found
*/
public static int linearSearch(int[] arr, int key) {
// Traverse through array
for (int i = 0; i < arr.length; i++) {
// Check if current element matches key
if (arr[i] == key) {
return i; // return index if found
}
}
return -1; // return -1 if element not found
}
}