Sol:
function getBinarySort(array, elmToSearch){
const binaryIndex = getBinarySortHelper(array, elmToSearch);
// console.log('111 binaryIndex for:'+ elmToSearch + " is:"+binaryIndex);
if (binaryIndex == -1 || binaryIndex == array.length -1) {
return binaryIndex;
}else {
for(let i = binaryIndex+1; i<= array.length-1;i++) {
// console.log('Inside for loop');
// console.warn('yeah')
if(array[i] !== elmToSearch) {
console.log('IS NT EQUAL')
return i-1;
}/* else {
console.log('IS EQUAL')
} */
}
}
}
function getBinarySortHelper(array, elmToSearch) {
let start = 0, end = array.length - 1, mid = Math.floor((start + end) / 2);
while(true){
if(elmToSearch < array[start] || elmToSearch > array[end]){
return -1;
} else if (elmToSearch == array[mid]) {
return mid;
} else if (elmToSearch < array[mid]) {
end = mid-1;
mid = Math.floor((start + end) / 2);
} else if (elmToSearch > array[mid]) {
start = mid+1;
mid = Math.floor((start + end) / 2);
}
}
}
var array = [1, 2,2,2,2, 3,3,3,3,3,3, 4, 5];
// var inputs = [4, 1, 2, 3, 4, 5, 0.5, 10, 4.1];
var inputs = [7];
inputs.forEach(function (input) {
var x = getBinarySort(array, input)
console.log("Final index for" + input+ ' is:' +x)
});