mirror of
https://github.com/trekhleb/javascript-algorithms.git
synced 2026-03-13 08:51:02 +08:00
Add binary search.
This commit is contained in:
35
src/algorithms/search/binary-search/binarySearch.js
Normal file
35
src/algorithms/search/binary-search/binarySearch.js
Normal file
@@ -0,0 +1,35 @@
|
||||
import Comparator from '../../../utils/comparator/Comparator';
|
||||
|
||||
/**
|
||||
* @param {*[]} sortedArray
|
||||
* @param {*} seekElement
|
||||
* @param {function(a, b)} [comparatorCallback]
|
||||
* @return {number}
|
||||
*/
|
||||
|
||||
export default function binarySearch(sortedArray, seekElement, comparatorCallback) {
|
||||
const comparator = new Comparator(comparatorCallback);
|
||||
|
||||
let startIndex = 0;
|
||||
let endIndex = sortedArray.length - 1;
|
||||
|
||||
while (startIndex <= endIndex) {
|
||||
const middleIndex = startIndex + Math.floor((endIndex - startIndex) / 2);
|
||||
|
||||
// If we've found the element just return its position.
|
||||
if (comparator.equal(sortedArray[middleIndex], seekElement)) {
|
||||
return middleIndex;
|
||||
}
|
||||
|
||||
// Decide which half to choose for seeking next: left or right one.
|
||||
if (comparator.lessThen(sortedArray[middleIndex], seekElement)) {
|
||||
// Go to the right half of the array.
|
||||
startIndex = middleIndex + 1;
|
||||
} else {
|
||||
// Go to the left half of the array.
|
||||
endIndex = middleIndex - 1;
|
||||
}
|
||||
}
|
||||
|
||||
return -1;
|
||||
}
|
||||
Reference in New Issue
Block a user