代码
public class TestSearch{
public static void main(String args[]){
int[] a = {1,3,5,7,8,9,12,34,56,88};
int i = 56;
if(binarySearch(a,i) == -1)
System.out.print("要查找的值不在源数据中!");
else
System.out.print("数据在数组中下标为"+binarySearch(a,i)+"的位置");
}
public static int binarySearch(int[] a,int num){
if(a.length==0)
return -1;
int startPos = 0;
int endPos = a.length - 1;
int m = (startPos + endPos) / 2;
while(startPos <= endPos){
if(num == a[m])
return m;
if(num > a[m])
startPos = m + 1;
if(num < a[m])
endPos = m - 1;
m = (startPos + endPos) / 2;
}
return -1;
}
}
简单的查找
public class TestSearch{
public static void main(String args[]){
int[] a = {1,3,5,7,8,9,12,34,56,88};
int i = 12;
if(search(a,i) == -1)
System.out.print("要查找的值不在源数据中!");
else
System.out.print(search(a,i));
}
public static int search(int[] a, int num) {
for(int i=0; i<a.length; i++) {
if(a[i] == num) return i;
}
return -1;
}
}
效果图