首页 > 代码库 > 二分法查找

二分法查找

 1 package com.learning.algorithm; 2  3 public class BinarySearch { 4      5     public int binSearch(int[] arrValue, int start, int end, int key){ 6         int result = -1; 7          8         int mid = (start+end)/2; 9         10         if(start > end){11             return result;12         }13         14         if(arrValue[mid]==key){15             result = mid;16         }else if(key<arrValue[mid]){17             result = binSearch(arrValue,start,mid-1,key);18         }else if(key>arrValue[mid]){19             result = binSearch(arrValue,mid+1,end,key);20         }21         22         return result;23     }24     25     public static void main(String[] args) {26         int[] arrValue = http://www.mamicode.com/{3,5,11,17,21,23,28,30,32,50,64,78,81,95,101}; 27         BinarySearch bs = new BinarySearch();28         int result = bs.binSearch(arrValue,0, arrValue.length-1, 17);29         System.out.println("the position of the array is :"+result);30     }31 }

 

二分法查找