Skip to content

Commit 38d263a

Browse files
Created BinarySearch.js (codinasion#2983)
Wrote a JavaScript program to Binary search a array
1 parent a02d3ae commit 38d263a

1 file changed

Lines changed: 22 additions & 0 deletions

File tree

dsa/binary-search/BinarySearch.js

Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,22 @@
1+
function BinarySearch(arr,target){ //Binary function
2+
let start = 0;
3+
let end = arr.length-1;
4+
let middle;
5+
while(start<=end){
6+
middle = Math.floor((start + end)/2);
7+
if(arr[middle] === target){
8+
return middle;
9+
}
10+
else if(arr[middle] > target){
11+
end = middle - 1;
12+
}
13+
else{
14+
start = middle + 1;
15+
}
16+
}
17+
return -1; //return -1 if element not found
18+
}
19+
20+
let arr = [10 ,20 ,30 ,40 ,50 ,60 ,70 ,80 ,90 ,100];
21+
let target = 30;
22+
console.log(BinarySearch(arr,target)); //2

0 commit comments

Comments
 (0)