展开
拓展 关闭
订阅号推广码
GitHub
视频
公告栏 关闭

二分查找

  • 必须是1个有序的数组
  • 第1次推导
public class test {
public static void main(String[] args) {
int[] ints = {1,2,3,5,7,9};
int a = 6; // 要查找的数
int i=0; //起始位置
int j=ints.length-1; // 结束位置
int m; // 中间位置
// 第1次查找
//[1][2][3][5][7][9]
// i m j
if(i<=j){
m = (i+j)/2; // 2
if(ints[m] < a){
i = m + 1; // 3
} else if (ints[m] > a){
j = m -1;
} else {
System.out.println("要查找的数的索引是" + m);
}
} // i=3,j=5
// 第2次查找
//[1][2][3][5][7][9]
// i m j
if(i<=j){
m = (i+j)/2; // 4
if(ints[m] < a){
i = m + 1;
} else if (ints[m] > a){
j = m -1; // 3
} else {
System.out.println("要查找的数的索引是" + m);
}
} // i=3,j=3
// 第3次查找
//[1][2][3][5][7][9]
// i|j
if(i<=j){
m = (i+j)/2; // 3
if(ints[m] < a){
i = m + 1; // 4
} else if (ints[m] > a){
j = m -1;
} else {
System.out.println("要查找的数的索引是" + m);
}
} // i=4,j=3
// 数组中没有要查找的数的情况
if(i>j){
System.out.println("数组中没有要查找的数");
}
}
}
  • 最终完善
public class test {
public static void main(String[] args) {
int[] ints = {1,2,3,5,7,9};
int a = 6; // 如果传入0或10则会报错
Find(a, ints);
}
public static int Find(int a, int[] ints){
int i=0; //起始位置
int j=ints.length-1; // 结束位置
int m; // 中间位置
while (i<=j){
m = (i+j)/2;
if(ints[m] < a){
i = m + 1;
} else if (ints[m] > a){
j = m -1;
} else {
System.out.println("要查找的数的索引是" + m);
break;
}
}
if(i>j){
System.out.println("数组中没有要查找的数");
}
return -1;
}
}
posted @   DogLeftover  阅读(5)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· DeepSeek 开源周回顾「GitHub 热点速览」
· 物流快递公司核心技术能力-地址解析分单基础技术分享
· .NET 10首个预览版发布:重大改进与新特性概览!
· AI与.NET技术实操系列(二):开始使用ML.NET
· 单线程的Redis速度为什么快?
历史上的今天:
2022-09-29 马踏棋盘算法
2022-09-29 弗洛伊德算法
2022-09-29 迪杰斯特拉算法
点击右上角即可分享
微信分享提示