Skip to content
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
31 changes: 31 additions & 0 deletions javascript/binarySeachAlgoritham.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
function binarySearch(sortedArray, key) {
let start = 0;
let end = sortedArray.length - 1;

while (start <= end) {
let middle = Math.floor((start + end) / 2);

if (sortedArray[middle] === key) {
// found the key
return middle;
} else if (sortedArray[middle] < key) {
// Search to the right of the array
start = middle + 1;
} else {
//Search to the left of the array
end = middle - 1;
}
}
// key not found
return -1;
}

const sortedArray = [2, 4, 5, 7, 9, 11];
const key = 9;
const keyAt = binarySearch(sortedArray, key);

if (keyAt < 0) {
console.log(`Key not found.`);
} else {
console.log(`Found Key :: ${key} at index :: ${keyAt}`);
}