@@ -10,12 +10,18 @@ import Comparator from '../../../utils/comparator/Comparator';
10
10
*/
11
11
12
12
export default function binarySearch ( sortedArray , seekElement , comparatorCallback ) {
13
+ // Let's create comparator from the comparatorCallback function.
14
+ // Comparator object will give us common comparison methods like equal() and lessThen().
13
15
const comparator = new Comparator ( comparatorCallback ) ;
14
16
17
+ // These two indices will contain current array (sub-array) boundaries.
15
18
let startIndex = 0 ;
16
19
let endIndex = sortedArray . length - 1 ;
17
20
21
+ // Let's continue to split array until boundaries are collapsed
22
+ // and there is nothing to split anymore.
18
23
while ( startIndex <= endIndex ) {
24
+ // Let's calculate the index of the middle element.
19
25
const middleIndex = startIndex + Math . floor ( ( endIndex - startIndex ) / 2 ) ;
20
26
21
27
// If we've found the element just return its position.
@@ -33,5 +39,6 @@ export default function binarySearch(sortedArray, seekElement, comparatorCallbac
33
39
}
34
40
}
35
41
42
+ // Return -1 if we have not found anything.
36
43
return - 1 ;
37
44
}