Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- /*
- Бинарный поиск ищет, разбивая ваш массив на все меньшие и меньшие куски, пока не найдет нужное значение. В отличие от обычного indexOf, который ищет слева направо в простой итерации. Статья Википедии о бинарном поиске объясняет это лучше всего (как всегда). Есть пара недостатков; Это будет медленнее с меньшими наборами данных (это необходимо доказать), и массив, который вы ищете, должен быть отсортирован .
- 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
- */
- /**
- * Performs a binary search on the host array. This method can either be
- * injected into Array.prototype or called with a specified scope like this:
- * binaryIndexOf.call(someArray, searchElement);
- *
- * @param {*} searchElement The item to search for within the array.
- * @return {Number} The index of the element which defaults to -1 when not found.
- */
- function binaryIndexOf(searchElement) {
- 'use strict';
- var minIndex = 0;
- var maxIndex = this.length - 1;
- var currentIndex;
- var currentElement;
- while (minIndex <= maxIndex) {
- currentIndex = (minIndex + maxIndex) / 2 | 0;
- currentElement = this[currentIndex];
- if (currentElement < searchElement) {
- minIndex = currentIndex + 1;
- }
- else if (currentElement > searchElement) {
- maxIndex = currentIndex - 1;
- }
- else {
- return currentIndex;
- }
- }
- return -1;
- }
Add Comment
Please, Sign In to add comment