Skip to content

Commit

Permalink
Merge pull request Asiatik#404 from ooHAoo/issue1
Browse files Browse the repository at this point in the history
Added Linear Search and Binary Search in Javascript
  • Loading branch information
ms10398 authored Nov 27, 2018
2 parents 05f73e1 + 153c648 commit da338f8
Show file tree
Hide file tree
Showing 2 changed files with 31 additions and 0 deletions.
21 changes: 21 additions & 0 deletions Searching/Binary Search/Javascript/BinarySearch.js
Original file line number Diff line number Diff line change
@@ -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
Original file line number Diff line number Diff line change
@@ -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;
}

0 comments on commit da338f8

Please sign in to comment.