I started learning algorithms in JavaScript recently. I was experimenting with binary search when I came across this question and I have been trying to implement it, but I keep having difficulties. The function takes two parameters(a sorted array and a number) and returns an object
containing the occurrence and count of the number. The occurrence
I'm getting is not the right occurrence of the number, and the count
is constant.
This is what I have done so far:
function binarySearchOccurrence(array, element) {
//declare the start index on the left side to zero
let startIndex = 0;
//declare the end index on the right side to the length of array minus 1
let endIndex = array.length - 1;
//set initial count to zero
let count = 0;
let occurrence = 0;
//declare an empty object to hold the result of search and count
const result = {}
//Applying binary search, iterate while start does not meed end
while(startIndex <= endIndex){
//find the middile index
let middle = Math.floor((startIndex + endIndex)/2);
let guessElement = array[middle];
count++;
//if element is present in the middle, increment occurence
if(guessElement === element){
occurrence++;
while(startIndex <= endIndex){
if(guessElement > element){
endIndex = middle - 1;
occurrence++;
break;
} else {
startIndex = middle + 1;
occurrence++;
break;
}
}
//Else look in the left or right side accordingly
} else if (guessElement > element) {
endIndex = middle - 1;
} else {
startIndex = middle + 1;
}
}
result.occurrence = occurrence;
result.count = count;
return result;
}
when I test with an array like this: binarySearchOccurrence([1, 2, 3, 4, 4, 4, 5, 5, 5, 6, 7, 8, 9], 5)
it returns { occurrence: 6, count: 4 }
instead of { occurrence: 3, count: 2 }
;