Binary Search using Python Bisect and Java Arrays.binarySearch()¶
In [1]:
import bisect
def binSearch(a, x):
# Return leftmost index of x
# If not found, return (negative proper index-1)
i = bisect.bisect_left(a, x)
if i!=len(a) and a[i] == x:
return i
else:
return -1*i-1
arr = [8,6,4,2]
arr.sort()
print(arr)
for i in range(11):
print(" ",i," found at index = ",binSearch(arr,i))
import java.util.Arrays;
public class bsdemo {
public static void main(String[] args)
{
int arr[] = {8,6,4,2};
Arrays.sort(arr);
System.out.println(Arrays.toString(arr));
for(int i=0; i<11;i++) {
System.out.println(" " + i + " found at index = "
+Arrays.binarySearch(arr,i));
}
}
}
[2, 4, 6, 8] 0 found at index = -1 1 found at index = -1 2 found at index = 0 3 found at index = -2 4 found at index = 1 5 found at index = -3 6 found at index = 2 7 found at index = -4 8 found at index = 3 9 found at index = -5 10 found at index = -5