-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathSearchingAlgorithms.java
More file actions
32 lines (28 loc) · 874 Bytes
/
SearchingAlgorithms.java
File metadata and controls
32 lines (28 loc) · 874 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
32
public class SearchingAlgorithms {
public static boolean linearSearchIterative(int[] a, int value) {
for(int i =0 ; i<a.length; i++)
if(a[i] == value)
return true;
return false;
}
public static boolean linearSearchRecursive(int[] a, int value, int index) {
if(a[index] == value)
return true;
else if(index>=a.length)
return false;
return linearSearchRecursive(a, value, index+1);
}
public static boolean binarySearchRecursive(int[] a, int value, int minIndex, int maxIndex) { //iterative not easy
int midIndex = (maxIndex + minIndex)/2;
if(minIndex>maxIndex)
return false;
else if(a[midIndex] == value)
return true;
else {
if(value>a[midIndex]) //upper half
return binarySearchRecursive(a, value, midIndex+1, maxIndex);
else //lower half
return binarySearchRecursive(a, value, minIndex, midIndex-1);
}
}
}