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 56e74e6

Browse files
committed
binary Search
1 parent 03a8059 commit 56e74e6

File tree

1 file changed

+16
-0
lines changed

1 file changed

+16
-0
lines changed

‎Algorithms/Searching/binarySearch.js

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,16 @@
1+
'use strict';
2+
function binarySearch(arr, k) {
3+
let low = 0, high = arr.length - 1;
4+
while (low <= high) {
5+
let mid = parseInt((low + high) / 2)
6+
if (k == arr[mid]) return mid;
7+
if (k < arr[mid]) high = mid - 1;
8+
if (k > arr[mid]) low = mid + 1;
9+
}
10+
return -1;
11+
}
12+
13+
let k = 8;
14+
let indexOfK = binarySearch([0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10], k);
15+
if (indexOfK != -1) console.log(k + ' found at index ' + indexOfK);
16+
else console.log(k + ' not found');

0 commit comments

Comments
(0)

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