Squash commit

This commit is contained in:
Tay Yang Shun
2017-09-20 15:27:28 +08:00
commit 2182a70770
70 changed files with 5486 additions and 0 deletions

26
utilities/binarySearch.js Normal file
View File

@ -0,0 +1,26 @@
function binarySearch(arr, target) {
let left = 0;
let right = arr.length - 1;
while (left < right) {
let mid = left + Math.floor((right - left) / 2);
if (arr[mid] === target) {
return mid;
}
if (arr[mid] < target) {
left = mid + 1;
} else {
right = mid - 1;
}
}
return left;
}
console.log(binarySearch([1, 2, 3, 10], 1) === 0)
console.log(binarySearch([1, 2, 3, 10], 2) === 1)
console.log(binarySearch([1, 2, 3, 10], 3) === 2)
console.log(binarySearch([1, 2, 3, 10], 10) === 3)
console.log(binarySearch([1, 2, 3, 10], 9) === 3)
console.log(binarySearch([1, 2, 3, 10], 4) === 3)
console.log(binarySearch([1, 2, 3, 10], 0) === 0)
console.log(binarySearch([1, 2, 3, 10], 11) === 3)
console.log(binarySearch([5, 7, 8, 10], 3) === 0)