-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathDicotomic.java
More file actions
56 lines (40 loc) · 1.37 KB
/
Copy pathDicotomic.java
File metadata and controls
56 lines (40 loc) · 1.37 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
import java.util.ArrayList;
import java.util.Scanner;
public class Dicotomic {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
ArrayList<Integer> arr = new ArrayList<Integer>(scanArray(in));
int key = in.nextInt();
System.out.println(binarySearch(arr, key));
}
public static int binarySearch(ArrayList<Integer> arr, int key) {
int pos = arr.size() / 2;
if(arr.size() < 1) {
if(arr.get(pos) == key) {
return pos;
} else {
System.out.println("-1");
}
}
if(arr.size() == 0) {
System.out.printl("-1");
}
if(arr.get(pos) == key) {
return pos;
} else if(arr.get(pos) < key) {
return (arr.size() / 2) + binarySearch(new ArrayList<Integer>(arr.subList(pos, arr.size())), key);
} else {
return binarySearch(new ArrayList<Integer>(arr.subList(0, pos)), key);
}
}
public static ArrayList<Integer> scanArray(Scanner in) {
String line = in.nextLine();
String[] tokens = line.split(" ");
ArrayList<Integer> arr = new ArrayList<Integer>();
for (String token : tokens) {
if (!token.isEmpty())
arr.add(Integer.parseInt(token));
}
return arr;
}
}