Skip to content
This repository has been archived by the owner on Oct 7, 2019. It is now read-only.

Commit

Permalink
Merge pull request #9 from smokyabdulrahman/js-binary-search
Browse files Browse the repository at this point in the history
JavaScript binary search - Issue #4
  • Loading branch information
senapati-deepak authored Oct 2, 2018
2 parents c3da325 + 4f2e33d commit cd0b817
Showing 1 changed file with 33 additions and 0 deletions.
33 changes: 33 additions & 0 deletions search/binary_search/JavaScript/binary_search.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
// takes sorted array and key
// returns index of key elemnt, -Infinity otherwise
function binarySearch(array, key) {
first = 0;
last = array.length;
middle = (first + last) / 2;
while (first <= last) {
// the middle value is smaller than wanted key
// search upper part insted.
if (array[middle] < key) {
first = middle + 1;
}
// the middle value is equal to wanted value
else if (array[middle] == key) {
return middle;
}
// the middle value is bigger than wanted key
// search lower part insted.
else {
last = middle - 1;
}

middle = (first + last) / 2;
}

// didn't find key
return Number.NEGATIVE_INFINITY;
}

sampleArray = [1, 2, 3, 4, 5, 6];
sampleKey = 2;

console.log(binarySearch(sampleArray, sampleKey));

0 comments on commit cd0b817

Please sign in to comment.