Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit 9bccfac

Browse files
author
Mohit Sharma
authored
Added Implementation of Binary Search
1 parent adbd6d7 commit 9bccfac

File tree

1 file changed

+27
-0
lines changed

1 file changed

+27
-0
lines changed

‎Search/binarySearch.js

Lines changed: 27 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,27 @@
1+
/*Binary Search-Search a sorted array by repeatedly dividing the search interval
2+
* in half. Begin with an interval covering the whole array. If the value of the
3+
* search key is less than the item in the middle of the interval, narrow the interval
4+
* to the lower half. Otherwise narrow it to the upper half. Repeatedly check until the
5+
* value is found or the interval is empty.
6+
*/
7+
8+
function binarySearch(arr, i) {
9+
var mid = Math.floor(arr.length / 2);
10+
if (arr[mid] === i) {
11+
console.log('match', arr[mid], i);
12+
return arr[mid];
13+
} else if (arr[mid] < i && arr.length > 1) {
14+
binarySearch(arr.splice(mid, Number.MAX_VALUE), i);
15+
} else if (arr[mid] > i && arr.length > 1) {
16+
binarySearch(arr.splice(0, mid), i);
17+
} else {
18+
console.log('not found', i);
19+
return -1;
20+
}
21+
22+
}
23+
24+
var ar=[1,2,3,4,5,6,7,8,9,10];
25+
binarySearch(ar,3);
26+
binarySearch(ar,7);
27+
binarySearch(ar,13);

0 commit comments

Comments
(0)

AltStyle によって変換されたページ (->オリジナル) /