suppose I have an array of 10 ints, and I’m using binary search to find a number, let’s take for example numbers
1 2 3 4 5 6 7 8 9 10
and I’m using this method
static void binarySearch(int n, int[] a, int low, int high)
{
int mid = (high + low) / 2;
if(low > high)
System.out.println(n+" was not found after "+counter+" comparisons");
else if(a[mid] == n)
{
counter++;
System.out.println(n+" was found at position "+mid+" after "+counter+" comparisons");
}
else if(a[mid] < n)
{
counter++;
binarySearch(n, a, mid+1, high);
}
else
{
counter++;
binarySearch(n, a, low, mid-1);
}
}
what is the proper way of calling the method binarySearch(5, a, 0, a.lenght)
or
binarySearch(5, a, 0, a.lenght-1)
I know they both will find the number, but they will find it at different index; thus taking more comparison
Well let’s do some tests shall we?
First, let’s search for each number in the array. We get:
binarySearch(i, array, 0, array.length);binarySearch(i, array, 0, array.length - 1);As you can see, variances do appear, but the average remains constant.
Now let’s test for bigger numbers:
Hence, on average it doesn’t go either way. For the sake of convention I would advise using the exclusive upper bound version:
binarySearch(i, array, 0, array.length);