利用Java实现折半查找
基本思路:while递归循环,不断判断a[middle]是否等于data,如果等于则跳出循环,返回索引值,如果不等,则进行二分处理,直至两者相等为止;其中通过count计数器记录查找次数,当count次数超过20次时视为元素不存在(此处有待优化)
package test; /* * 二分法查找(折半查找) * TGmoving * */ public class halfSearch { public static int HalfSearch(int a[],int data){ int length = a.length; int start = 0; int end = length - 1; int middle = (start + end) / 2; int count = 1; //用于计数,折半查找次数超过20次仍未找到视为不存在该元素 while(data!=a[middle]){ if(start > end || count > 20){ return -1; }else{ if(data < a[middle]){ end = middle; middle = (start + end) / 2; System.out.println("第"+(count+1)+"次查找 data < a[middle]: "+ "索引为:"+middle); }else if(data > a[middle]){ start = middle + 1; middle = (start + end ) / 2; System.out.println("第"+(count+1)+"次查找 data > a[middle]: "+ "索引为:"+middle); } } count++; } count = 0; return middle; } public static void main(String[]Args){ int a[] = {1,2,3,4,5,6,7}; int index = HalfSearch(a, 7); System.out.println("isExist:"+ index ); } }
运行结果展示:
时间: 2024-11-06 12:32:40