GeezerVison is showing github.com — Add comments to binarySearch function. · BrandonWeb/javascript-algorithms@243be8f
File tree
Expand file treeCollapse file tree
Open diff view settings
src/algorithms/search/binary-search
Expand file treeCollapse file tree
Open diff view settings
Collapse file
Copy file name to clipboardExpand all lines: src/algorithms/search/binary-search/binarySearch.js +7Lines changed: 7 additions & 0 deletions | Original file line number | Diff line number | Diff line change |
|---|
@@ -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 | } |