Created
March 31, 2022 12:07
-
-
Save prav-raghu/7c74a3353c8e8ca0c57b832306d8c8b4 to your computer and use it in GitHub Desktop.
iterativeBinarySearch
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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