二分查找法前提是数组已经有序,如果无序则不能使用二分查找
java实现如下:
package problem.search;
public class BinarySearch {
public static int binarySearch(int[] arr,int val)
{
int left=0;
int right=arr.length-1;
int mid=0;
while(left<=right)
{
mid=(left+right)/2;
if(arr[mid]==val)
{
return mid;
}
if (arr[mid]<val)
{
left=mid+1;
}
if (arr[mid]>val)
{
right=mid-1;
}
}
return -1;
}
public static void main(String[] args) {
int[] arr={1,2,3,4,5,6,7,8,9,10};
int index=binarySearch(arr,7);
System.out.println(index);
}
}
执行结果如下:
6