二分查找(折半查找)
前提:排好顺序的数据
//元素存在 返回索引,否则返回-1
public static int binarySearch(int[] arr, int data) {
int left = 0;
int right = arr.length - 1;
while(left <= right){//当左边索引大于右边时仍未找到data则元素不存在
int mid = (left + right) / 2;
if (arr[mid] < data){//中间索引处的值比要查找的值小
left = mid + 1;//将左边索引更新为中间索引+1,反之right=mid-1
} else if (arr[mid] > data){
right = mid - 1;
} else if (arr[mid] == data){
return mid;
}
}
return -1;
}
标签:二分,arr,int,mid,查找,data
From: https://www.cnblogs.com/10525blogs/p/16846840.html