Skip to content

Commit da338f8

Browse files
authored
Merge pull request #404 from ooHAoo/issue1
Added Linear Search and Binary Search in Javascript
2 parents 05f73e1 + 153c648 commit da338f8

File tree

2 files changed

+31
-0
lines changed

2 files changed

+31
-0
lines changed
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,21 @@
1+
/** Binary search algorithm in Javascript **/
2+
/** Follows the README.md **/
3+
4+
function binarySearch(array, target) {
5+
let leftIndex = 0;
6+
let rightIndex = array.length - 1;
7+
let middleIndex;
8+
9+
while (leftIndex <= rightIndex) {
10+
middleIndex = leftIndex + Math.floor((rightIndex - leftIndex) / 2);
11+
if (array[middleIndex] === target) {
12+
return middleIndex;
13+
}
14+
if (arr[middleIndex] < target) {
15+
leftIndex = middleIndex + 1;
16+
} else {
17+
rightIndex = middleIndex - 1;
18+
}
19+
}
20+
return -1;
21+
}
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,10 @@
1+
/** Binary search algorithm in Javascript **/
2+
3+
function linearSearch(array, item) {
4+
for (let i = 0; i < array.length; i++) {
5+
if(array[i] === item) {
6+
return i;
7+
}
8+
}
9+
return -1;
10+
}

0 commit comments

Comments
 (0)