prantiknoor

Binary search in typescript

Mar 4th, 2023
56
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
TypeScript 0.70 KB | Source Code | 0 0
  1. function binarySearch(array: Array<any>, compare: Function) {
  2.     let low = 0, high = array.length;
  3.  
  4.     do {
  5.         let mid = Math.round((low + high) / 2);
  6.         let result = compare(array[mid]);
  7.  
  8.         if (result === 'left') {
  9.             high = mid - 1;
  10.         } else if (result === 'right') {
  11.             low = mid + 1;
  12.         } else {
  13.             return mid;
  14.         }
  15.     } while (low <= high);
  16.     return -1;
  17. }
  18.  
  19. const array = [];
  20. for(let i = 1; i <= 10**6; i++) array.push({value: i});
  21. const item = 6;
  22. let count = 0;
  23.  
  24. const index = binarySearch(array, (midItem: {value: number}) => {
  25.     console.log('Count: ' + ++count);
  26.     if (midItem.value > item) return 'left';
  27.     if (midItem.value < item) return 'right';
  28.     return 'found';
  29. });
  30.  
  31. console.log(index);
Advertisement
Add Comment
Please, Sign In to add comment