Praktikum_mf

Бинарный поиск

Mar 30th, 2021
670
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. // const list = [1, 3, 4, 5, 7, 10];
  2.  
  3. function binarySearch(list, element) {
  4.   let first = 0;
  5.   let last = list.length;
  6.   let position = -1;
  7.   while (first < last) {
  8.     const mid = Math.floor((first + last) / 2);
  9.     if (list[mid] === element) {
  10.       position = mid;
  11.     }
  12.     if (list[mid] < element)
  13.       first = mid + 1;
  14.     else {
  15.       last = mid;
  16.     }
  17.   }
  18.   return position;
  19. }
Advertisement
Add Comment
Please, Sign In to add comment