, , , , .
- , .
n [] = {1, 2, 4, 6, 8, 10, 12, 14, 16, 18, 20}
: 2,
1: = 10, = 0, = 5
2: = 5, = 0, = 2
3: = 2, = 0, med = 1 . 1.
: 3 ( ),
1: = 10, = 0, = 5
2: = 5, = 0, = 2
3: = 2, = 0, = 1
4: = 1, = 0, = + 1, . , med = 1.
, ...
public static <T> int binarySearch(List<T> list, T key, Comparator<T> compare) {
int low, high, med, c;
T temp;
high = list.size();
low = 0;
med = (high + low) / 2;
while (high != low+1) {
temp = list.get(med);
c = compare.compare(temp, key);
if (c == 0) {
return med;
} else if (c < 0){
low = med;
}else{
high = med;
}
med = (high + low) / 2;
}
return med;
}
public static void main(String[] args) {
List<Integer> nos = new ArrayList<Integer>();
nos.addAll(Arrays.asList(new Integer[]{1, 2, 4, 6, 8, 10, 12, 14, 16, 18, 20}));
search(nos, 2);
search(nos, 3);
search(nos, 10);
search(nos, 11);
}
public static void search(List<Integer> nos, int search){
int key = binarySearch(nos, search, new IntComparator());
System.out.println("Search:"+search+"\tKey:"+key+"\tValue:"+nos.get(key));
}
public static class IntComparator implements Comparator<Integer>{
@Override
public int compare(Integer o1, Integer o2) {
return o1.compareTo(o2);
}
}