-
Notifications
You must be signed in to change notification settings - Fork 4
Expand file tree
/
Copy pathLinearSearch.java
More file actions
31 lines (28 loc) Β· 846 Bytes
/
Copy pathLinearSearch.java
File metadata and controls
31 lines (28 loc) Β· 846 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
package day5;
public class LinearSearch {
/*
time complexity: O(1)
space complexity: O(1)
*/
public static void main(String[] args) {
System.out.println(linearSearch(new int[] {1, 2, 3, 4, 5}, 4));
System.out.println(linearSearch(new int[] {1, 2, 3, 4, 5}, 100));
System.out.println(linearSearch(new int[] {1, 2, 3, 4, 2, 2, 5, 2}, 2));
}
/*
Linear Search
{1, 2, 3, 4} elem=3 index=2
{2, 3, 5, 7,11} elem=2 index=0
{-10, 0, 9, 3, 45} elem=90 index=-1
time complexity: O(n)
space complexity: O(1)
*/
private static int linearSearch(int[] array, int element) {
for (int i = 0; i < array.length ; i++) {
if (array[i] == element) {
return i;
}
}
return -1;
}
}