-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbinarySearch.java
More file actions
29 lines (28 loc) · 881 Bytes
/
binarySearch.java
File metadata and controls
29 lines (28 loc) · 881 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
import org.json.JSONArray;
public class binarySearch {
public int search(JSONArray dataArray,String searchElement){
try{
int lowerBound = 0;
int upperBound = dataArray.length() - 1;
while (lowerBound <= upperBound){
int mid = lowerBound + (upperBound - lowerBound) / 2;
System.out.println(mid);
int compareValue = searchElement.compareTo(dataArray.getString(mid));
if(compareValue == 0){
return mid;
}
if(compareValue > 0){
lowerBound = mid + 1;
}
else{
upperBound = mid - 1;
}
}
return -1;
}
catch (Exception e){
e.printStackTrace();
return -1;
}
}
}