Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Create binary search.js #381

Open
wants to merge 1 commit into
base: main
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
37 changes: 37 additions & 0 deletions binary search.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,37 @@
// Iterative function to implement Binary Search
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;
}

// Driver code
let arr = [1, 3, 5, 7, 8, 9];
let x = 5;

if (iterativeFunction(arr, x, 0, arr.length-1))
document.write("Element found!<br>");
else document.write("Element not found!<br>");

x = 6;

if (iterativeFunction(arr, x, 0, arr.length-1))
document.write("Element found!<br>");
else document.write("Element not found!<br>");