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 }