Skip to content

Instantly share code, notes, and snippets.

@prav-raghu
Created March 31, 2022 12:07
Show Gist options
  • Save prav-raghu/7c74a3353c8e8ca0c57b832306d8c8b4 to your computer and use it in GitHub Desktop.
Save prav-raghu/7c74a3353c8e8ca0c57b832306d8c8b4 to your computer and use it in GitHub Desktop.
iterativeBinarySearch
var array = [1,2,3,4,5]
let iterativeFunction = function (arr, x) {
let start=0, end=arr.length-1;
// Iterate while start not meets end
while (start<=end){
// Find the mid index
let mid=Math.floor((start + end)/2);
// If element is present at mid, return True
if (arr[mid]===x) return true;
// Else look in left or right half accordingly
else if (arr[mid] < x)
start = mid + 1;
else
end = mid - 1;
}
return false;
}
console.log(iterativeFunction(array,4))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment