Skip to content

Commit 844c331

Browse files
author
Nicholas C. Zakas
committed
Second take: Binary search algorithm
1 parent fdd3c10 commit 844c331

File tree

1 file changed

+4
-5
lines changed

1 file changed

+4
-5
lines changed

algorithms/searching/binary-search/binary-search.js

Lines changed: 4 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -31,8 +31,8 @@
3131
function binarySearch(items, value){
3232

3333
var startIndex = 0,
34-
middle = Math.floor(items.length / 2),
35-
stopIndex = items.length;
34+
stopIndex = items.length - 1,
35+
middle = Math.floor((stopIndex + startIndex)/2);
3636

3737
while(items[middle] != value && startIndex < stopIndex){
3838

@@ -44,10 +44,9 @@ function binarySearch(items, value){
4444
}
4545

4646
//recalculate middle
47-
middle = Math.floor((stopIndex + startIndex)/2);
48-
47+
middle = Math.floor((stopIndex + startIndex)/2);
4948
}
5049

5150
//make sure it's the right value
5251
return (items[middle] != value) ? -1 : middle;
53-
}
52+
}

0 commit comments

Comments
 (0)