publicclassMain{publicstaticvoidmain(String[]args){Bar[]bars={newBar(12),newBar(23),newBar(34),newBar(45),newBar(56),newBar(67),newBar(78),newBar(89)};System.out.println(...
public class Main {
public static void main(String[] args) {
Bar[] bars = {new Bar(12), new Bar(23), new Bar(34), new Bar(45),
new Bar(56), new Bar(67), new Bar(78), new Bar(89)};
System.out.println(bsearch(bars, new Bar(12)));
System.out.println(ssearch(bars, new Bar(12)));
}
public static > int bsearch(T[] array, T key) {
return bsearch(array, key, 0, array.length-1);
}
public static > int bsearch(T[] array, T key, int left, int right) {
int cmp, middle = right / 2;
if (left > right) {
return -1;
}
else if ((cmp = key.compareTo(array[middle])) == 0) {
return middle;
}
else if (cmp < 0) {
return bsearch(array, key, left, middle-1);
}
else {
return bsearch(array, key, middle+1, right);
}
}
public static > int ssearch(T[] array, T key) {
return ssearch(array, key, 0);
}
private static > int ssearch(T[] array, T key, int index) {
if (index >= array.length) {
return -1;
}
else if (array[index].compareTo(key) == 0) {
return index;
}
return ssearch(array, key, index+1);
}
}
class Foo implements Comparable {
public Foo(int foo) {
this.foo = foo;
}
public int compareTo(Foo other) {
return foo - other.foo;
}
public String toString() {
return Integer.toString(foo);
}
private int foo;
}
class Bar extends Foo {
public Bar(int bar) {
super(bar);
this.bar = bar;
}
private int bar;
}
展开