二分搜索的思路:
二分搜索的前提是需要待搜索的数组是有序的,令A[low…high]为元素按升序排列的非空数组,A[mid]为中间元素,x为给定元素,假定x>A[mid],那么,x肯定在A[mid+1],…,A[high]中,接下来只需在A[mid+1…high]中搜索x即可。类似的,如果x
<
<script type="math/tex" id="MathJax-Element-1"><</script>A[mid],只需在A[low..mid-1]中搜索x。重复此过程,直到找到元素x或者当前数组长度为0为止。
二分搜索的实现:
/**
* 二分搜索
* Created by yuzhan on 2017/10/18.
*/
public class main {
public static int BinarySearch(int[] A,int x){
int low = 0;
int high = A.length-1;
int j = 0;
while (low <= high){
int mid = (low+high)/2;
if(x == A[mid]) {
j = mid;
break;
}else if(x < A[mid])
high = mid - 1;
else
low = mid + 1;
}
if(j != 0)
return j;
else
return -1;
}
public static void main(String[] args) {
int[] A = {1,2,3,6,14,23,65,75,134,167,232};
int x = 75;
int index = main.BinarySearch(A,x);
System.out.print(index);
}
}