编写一个二分法查找的函数返回值为查到数据的下标,如果没有找到返回-1
1个回答
展开全部
public class Test {
private int find(int[] d, int n) {
int low = 0;
int high = d.length - 1;
int key = 0;
int index = -1;
while (low <= high) {
key = (low + high) / 2;
if (d[key] == n) {
index = key;
break;
} else if (d[key] > n) {
high = key - 1;
} else {
low = key + 1;
}
}
return index;
}
public static void main(String[] args) {
// TODO Auto-generated method stub
Test test = new Test();
int[] aa = new int[] { -1,1, 3, 22, 45, 55, 343, 452 };
int i = test.find(aa, 4);
System.out.println(i);
}
}
private int find(int[] d, int n) {
int low = 0;
int high = d.length - 1;
int key = 0;
int index = -1;
while (low <= high) {
key = (low + high) / 2;
if (d[key] == n) {
index = key;
break;
} else if (d[key] > n) {
high = key - 1;
} else {
low = key + 1;
}
}
return index;
}
public static void main(String[] args) {
// TODO Auto-generated method stub
Test test = new Test();
int[] aa = new int[] { -1,1, 3, 22, 45, 55, 343, 452 };
int i = test.find(aa, 4);
System.out.println(i);
}
}
本回答被网友采纳
已赞过
已踩过<
评论
收起
你对这个回答的评价是?
推荐律师服务:
若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询