JAVA中运用数组的折半查找算法



java中在应用折半查找时,先要判断数组是否为空,如果为空就返回0结束查找。如果不为空,就设置两个整型数据记录数组的起始点和结束点。通过二分法得到一个中间点的数值,将所要查找的数据与这个点的数据进行比较,通过不断的这样操作,最终会找到这个点,然后返回这个值所在数组中的下标。如果没找到这个数值,则返回false。

下面是折半查找的具体算法供大家参考。

折半查找:

复制代码
 1  public static String binarySearch(int[] a,int num){
 2                 if (a.length==0)
 3                         return "Eroor";
 4                         int startPos=0;
 5                         int endPos=a.length-1;
 6                         int m=(startPos+endPos)/2;
 7                         while(startPos<=endPos){
 8                                 if (num==a[m]){
 9                                         return "所查数在数组的下标为"+m;
10                                 }else if (num>a[m]){
11                                         startPos=m+1;
12                                 }else if (num<a[m]){
13                                         endPos=m-1;
14                                 }
15                                 m=(startPos+endPos)/2;
16                         }
17                         return "数组中无该数值";
18         }
复制代码

折半查找的递归算法:

复制代码
 1 public static int binarySearch(int[] args, int i, int startPos, int endPos) {
 2 
 3                 if(args==null || startPos>endPos)
 4                         return -1;
 5                 
 6                 int midPos = (startPos+endPos) / 2;
 7                 if(i==args[midPos]) {
 8                         return midPos;
 9                 } else if(i<args[midPos]) {
10                         return binarySearch(args, i, startPos, midPos - 1);
11                 } else {
12                         return binarySearch(args, i, midPos + 1, endPos);
13                 }
14         }
复制代码



  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值