java 二分法查找某一元素

import java.util.ArrayList;
import java.util.List;


public class BinaryFind {


public int find(List a, int searchKey) {
// a's start index
int startIndex = 0;
// a's end index
int endIndex = a.size()-1 ;
int currIn;
while (true) {
currIn = (endIndex + startIndex) / 2;
if ((Integer)a.get(currIn)== searchKey) {
return currIn;
} else if (startIndex > endIndex) {
return -1;
} else {
if ((Integer)a.get(currIn) < searchKey) {
startIndex = currIn + 1;
} else {
endIndex = currIn - 1;
}
}
}


}



public void display(List list){
for(int i=0;i<list.size();i++){
System.out.println(list.get(i));
}
}

public static void main(String[] args) {
BinaryFind bs = new BinaryFind();

List list =new ArrayList();
list.add(1);
list.add(8);
list.add(10);
list.add(60);
list.add(66);
list.add(70);
list.add(80);
list.add(800);
bs.display(list);
int searchKey = 80;

// System.out.println(bs.find( searchKey)+"---");
System.out.println("=="+ bs.find(list,searchKey));

}
}

你可能感兴趣的:(java,list,String,Integer,Class,import)