-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathExample2.java
68 lines (47 loc) · 1.36 KB
/
Example2.java
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
63
64
65
66
67
68
package applications.algorithms;
import java.util.ArrayList;
/** Category: Algorithms
* ID: Example 2
* Description: Vanilla implementation of binary search
* Taken From:
* Details:
* TODO
*/
public class Example2 {
/**
* Search if the list contains the given value
*/
public static int search(final ArrayList<Integer> list, int value){
int low = 0;
int high = list.size()-1;
while( low != high){
int middle = (low + high)/2;
if( list.get(middle) < value){
// move to larger items
low = middle + 1 ;
}
else{
high = middle ;
}
}
if(list.get(high) >= value){
return high;
}
return -1;
}
public static void main(String[] args){
ArrayList<Integer> list = new ArrayList<>();
for(int i=0; i< 15; ++i){
list.add(i);
}
int value = 0;
int idx = Example2.search(list, value);
System.out.println("Value " + value + " is at index: "+idx);
value = 14;
idx = Example2.search(list, value);
System.out.println("Value " + value + " is at index: "+idx);
value = 7;
idx = Example2.search(list, value);
System.out.println("Value " + value + " is at index: "+idx);
}
}