java
public class BinarySearch {
public static void main(String[] args) {
int[] arr = { 11, 22, 33, 44, 55, 66, 77 };
int index = getIndex(arr, 33);
System.out.println("index:" + index);
}
public static int getIndex(int[] arr, int value) {
int l=0,h= arr.length - 1;
while (l<=h) {
int mid=l+(h-l)/2;
if (value==arr[mid]) return mid;
if (value<arr[mid]) h=mid-1;
else l=mid+1;
}
return -1;
}
}
python
def bin_search(data, val):
l= 0
h= len(list) - 1
while l<= h:
mid =l+ (h - l) / 2
if data[mid] == val:
return mid
elif data[mid] > val:
h= mid - 1
else:
l= mid + 1
return -1