package com.test4; /** * @author qingfeng * 功能:二分查找 */ public class BinarySearch { public static void main(String[] args) { // TODO Auto-generated method stub int[] arr = {2,7,56,78,22}; BSearch bs = new BSearch(); bs.search(0, arr.length-1, 78, arr); } } class BSearch { //key为待查找的值 public void search(int leftIndex, int rightIndex,int key,int arr[]) { if(leftIndex <= rightIndex)//递归条件 { int mid = (leftIndex+rightIndex)/2;//找到中值 { if(key == arr[mid]) { System.out.println("要找的值位置为"+mid); } else if(key < arr[mid]) { search(leftIndex,mid-1,key,arr); } else if(key > arr[mid]) { search(mid+1,rightIndex,key,arr); } } } } }