binary search in js
function binarySearchIndex (array, target, low = 0, high = array.length - 1) {
if (low > high) {
return -1
}
const midPoint = Math.floor((low + high) / 2)
if (target < array[midPoint]) {
return binarySearchIndex(array, target, low, midPoint - 1)
} else if (target > array[midPoint]) {
return binarySearchIndex(array, target, midPoint + 1, high)
} else {
return midPoint
}
}let arr = [1, 3, 5, 7, 8, 9];
let binarySearch = (arr, x , strt, end) => {
if(end < strt) return false;
let mid = Math.floor((strt + end) / 2);
if(arr[mid] === x) {
return true;
}
if(arr[mid] < x) {
return binarySearch(arr, x, mid+1, end);
}
if(arr[mid] > x) {
return binarySearch(arr, x , strt, mid-1);
}
}
let strt = 0, end = arr.length -1;
let bool = binarySearch(arr, 7, strt, end);
console.log(bool);
Also in JavaScript:
- js input trigger change event when set value with js
- REPLACE BROKEN IMAGES WITH A DEFAULT IMAGE
- javascript group array of objects lodash
- express get host url
- json placholder
- how to make a dictionary javascript
- how to access viewmodel in jquery
- hi;ight word in textarea javascript
- nodejs response is html not json data
- click on button submitting the form in angular
- how to create react native project at specific version
- sort date array javascript
- javascript context color
- search input at array javascript
- horizontal tabs in react js
- array.splice javascript
- jquery async await $.getScript(
- best way to learn js
- add countdown timer to javascript quiz
- 'unix_socket' => '/Applications/MAMP/tmp/mysql/mysql.sock',
- devexpress dxdatagrid custom text field link
- convert json to csv npm
- cancel settimeout
- document queryselectorall and map javacript