Skip to content

Instantly share code, notes, and snippets.

@AyemunHossain
Last active July 12, 2023 16:56
Show Gist options
  • Save AyemunHossain/df1537d00d8ceccd7c7deeb7b429ae98 to your computer and use it in GitHub Desktop.
Save AyemunHossain/df1537d00d8ceccd7c7deeb7b429ae98 to your computer and use it in GitHub Desktop.
Modified Binary Search Implementation
//The main concept of this modified binary search is: Normal bianary searh but we understand that not alwasy the element
//we want will be in the data set, so we keep calm and return the lower closest element of that searching element.
const modifiedBinarySearch = (arr, left, right, element) => {
if (left > right) {
return left - 1;
}
let mid = Math.floor((right + left) / 2);
if (arr[mid] == element) return mid;
else if (arr[mid] > element)
return modifiedBinarySearch(arr, left, right - 1, element);
else if (arr[mid] < element)
return modifiedBinarySearch(arr, left + 1, right, element);
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment