earthhouge 2015-12-28
简介: 二分查找算法是针对有序数组进行查找某个元素的算法,时间复杂度为Ο(logn) 。
public int search(int[] arr,int x) throws Exception{ int start = 0; int end = arr.length-1; while(start<=end){ int mid = (start+end)/2; if(arr[mid]>x){ end = mid-1; }else if(arr[mid] == x){ return mid; }else if(arr[mid]<x){ start = mid+1; } } throw new Exception("not found"+x); }