Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- function binarySearch(array: Array<any>, compare: Function) {
- let low = 0, high = array.length;
- do {
- let mid = Math.round((low + high) / 2);
- let result = compare(array[mid]);
- if (result === 'left') {
- high = mid - 1;
- } else if (result === 'right') {
- low = mid + 1;
- } else {
- return mid;
- }
- } while (low <= high);
- return -1;
- }
- const array = [];
- for(let i = 1; i <= 10**6; i++) array.push({value: i});
- const item = 6;
- let count = 0;
- const index = binarySearch(array, (midItem: {value: number}) => {
- console.log('Count: ' + ++count);
- if (midItem.value > item) return 'left';
- if (midItem.value < item) return 'right';
- return 'found';
- });
- console.log(index);
Advertisement
Add Comment
Please, Sign In to add comment