给定一个有序整型数组, 实现二分查找
public class Test40 { public static void main(String[] args) { int[] arr={1,2,3,4,5,6,7,8}; int tofind=4; toSearch(arr,tofind); } private static void toSearch(int[] arr, int tofind) { int left=0; int right=arr.length-1; int mid; while(left<=right){ mid=(left+right)/2; if(arr[mid]>tofind){ right=mid-1; } else if(arr[mid]<tofind){ left=mid+1; } else { System.out.println("已查找到该值:"+arr[mid]); break; } System.out.println("查无此值"); break; } } }
实现结果: