Hi,
what is the index of the search key if we search for 24 in the following array using binary search.
array = [10,20,21,24,24,24,24,24,30,40,45]
For the sake of completeness here's an example in typescript, non-recursive version (binary operators are used to enforce operations on integers rather than floating-point arithmetic) Example is easily convertible to other C-like languages:
function binarySearch(array: number[], query: number): [number, number] {
let from: number;
let till: number;
let mid = 0 | 0;
let min = 0 | 0;
let max = array.length - 1 | 0;
while (min < max) {
mid = (min + max) >>> 1;
if (array[mid] < query) {
min = mid + 1 | 0;
} else {
max = mid - 1 | 0;
}
}
mid = min;
min--;
max++;
from = array[mid] < query ? (array[max] === query ? max : mid) : (array[mid] === query ? mid : min);
min = 0 | 0;
max = array.length - 1 | 0;
while (min < max) {
mid = (min + max) >>> 1;
if (query < array[mid]) {
max = mid - 1 | 0;
} else {
min = mid + 1 | 0;
}
}
mid = min;
min--;
max++;
till = array[mid] > query ? (array[min] === query ? min : mid) : (array[mid] === query ? mid : max);
return [from, till];
}
Here's how it can be used:
let array = [1, 3, 3, 3, 5, 5, 5, 5, 5, 5, 7];
console.log(binarySearch(array, 0)); // Gives [ -1, 0 ] <= No value found, note that resulting range covers area beyond array boundaries
console.log(binarySearch(array, 1)); // Gives [ 0, 0 ] <= Singular range (only one value found)
console.log(binarySearch(array, 2)); // Gives [ 0, 1 ] <= Queried value not found, however the range covers argument value
console.log(binarySearch(array, 3)); // Gives [ 1, 3 ] <= Multiple values found
console.log(binarySearch(array, 4)); // Gives [ 3, 4 ] <= Queried value not found, however the range covers argument value
console.log(binarySearch(array, 5)); // Gives [ 4, 9 ] <= Multiple values found
console.log(binarySearch(array, 6)); // Gives [ 9, 10 ] <= Queried value not found, however the range covers argument value
console.log(binarySearch(array, 7)); // Gives [ 10, 10 ] <= Singular range (only one value found)
console.log(binarySearch(array, 8)); // Gives [ 10, 11 ] <= No value found, note that resulting range covers area beyond array boundaries