1standLastOccurenceOfElement
by Krishna Ananthi
HTML
//given sorted array [1,2,2,2,2,3,4,3] find 3 o/p 4,6
wrong implementation //link https://www.youtube.com/watch?v=J7mV8YIs4u8&list=PLL0W8x08fpnVcdDoA9V-CJDZQElqy9PD1&index=4
JavaScript
function findELementFirstOccurence(arr, key, first) {
let s = 0,
e = arr.length,
mid;
while (s < e) {
mid = Math.floor((s + e) / 2);
console.log(s, e, mid)
if (arr[mid] === key) {
if (first === true && arr[mid - 1] === key) { //multiple occurence found
e = mid - 1; //first occurrence
} else if (first === false && arr[mid + 1] === key) {
s = mid + 1;
} else {
return mid; //only one occurrence
}
} else if (arr[mid] > key) {
e = mid - 1;
} else {
s = mid + 1;
}
}
return -1;
}
console.log(findELementFirstOccurence([1, 2, 3, 3, 3, 4, 5], 3, false))