数据结构二分法

这是一个Java实现的二分查找算法,通过不断缩小搜索范围,直到找到目标值或者搜索区间变为0。如果找到目标值,返回其在数组中的下标;否则,返回-1表示未找到。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

  1. package per;   
  2.   
  3. public class Array1 {   
  4.     public int find(int searchKey, int[] array) {   
  5.         int lowBound = 0;   
  6.         int uppBound = array.length - 1;   
  7.   
  8.         int curIndex;   
  9.         while (true) {   
  10.             curIndex = (lowBound + uppBound) / 2;   
  11.             if (array[curIndex] == searchKey) {   
  12.                 return curIndex;                        //查找到数据,返回下标
  13.             } else if (lowBound > uppBound) {   
  14.                 break;                                  //未查找到数据   
  15.             } else{   
  16.                 if (array[curIndex] < searchKey) {   
  17.                     lowBound = curIndex+1;              //二分法 处于大的一半   
  18.                 } else {   
  19.                     uppBound = curIndex-1;              //二分法 处于小的一半   
  20.                 }   
  21.             }   
  22.         }   
  23.         return -1;                                      //未找到则返回-1
  24.     }   
  25.   
  26. }  
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值