volond

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

Jan 19th, 2022 (edited)
217
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. /*
  2. Бинарный поиск ищет, разбивая ваш массив на все меньшие и меньшие куски, пока не найдет нужное значение. В отличие от обычного indexOf, который ищет слева направо в простой итерации. Статья Википедии о бинарном поиске объясняет это лучше всего (как всегда). Есть пара недостатков; Это будет медленнее с меньшими наборами данных (это необходимо доказать), и массив, который вы ищете, должен быть отсортирован .
  3. http://webcache.googleusercontent.com/search?q=cache:64dZTZJuxC4J:oli.me.uk/2013/06/08/searching-javascript-arrays-with-a-binary-search/+&cd=2&hl=ru&ct=clnk&gl=ua
  4. */
  5. /**
  6.  * Performs a binary search on the host array. This method can either be
  7.  * injected into Array.prototype or called with a specified scope like this:
  8.  * binaryIndexOf.call(someArray, searchElement);
  9.  *
  10.  * @param {*} searchElement The item to search for within the array.
  11.  * @return {Number} The index of the element which defaults to -1 when not found.
  12.  */
  13. function binaryIndexOf(searchElement) {
  14.     'use strict';
  15.  
  16.     var minIndex = 0;
  17.     var maxIndex = this.length - 1;
  18.     var currentIndex;
  19.     var currentElement;
  20.  
  21.     while (minIndex <= maxIndex) {
  22.         currentIndex = (minIndex + maxIndex) / 2 | 0;
  23.         currentElement = this[currentIndex];
  24.  
  25.         if (currentElement < searchElement) {
  26.             minIndex = currentIndex + 1;
  27.         }
  28.         else if (currentElement > searchElement) {
  29.             maxIndex = currentIndex - 1;
  30.         }
  31.         else {
  32.             return currentIndex;
  33.         }
  34.     }
  35.  
  36.     return -1;
  37. }
Add Comment
Please, Sign In to add comment