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

Added Linear Search and Binary Search in Javascript #404

Merged
merged 1 commit into from Nov 27, 2018
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
21 changes: 21 additions & 0 deletions Searching/Binary Search/Javascript/BinarySearch.js
@@ -0,0 +1,21 @@
/** Binary search algorithm in Javascript **/
/** Follows the README.md **/

function binarySearch(array, target) {
let leftIndex = 0;
let rightIndex = array.length - 1;
let middleIndex;

while (leftIndex <= rightIndex) {
middleIndex = leftIndex + Math.floor((rightIndex - leftIndex) / 2);
if (array[middleIndex] === target) {
return middleIndex;
}
if (arr[middleIndex] < target) {
leftIndex = middleIndex + 1;
} else {
rightIndex = middleIndex - 1;
}
}
return -1;
}
10 changes: 10 additions & 0 deletions Searching/Linear Search/Javascript/LinearSearch.js
@@ -0,0 +1,10 @@
/** Binary search algorithm in Javascript **/

function linearSearch(array, item) {
for (let i = 0; i < array.length; i++) {
if(array[i] === item) {
return i;
}
}
return -1;
}