const container = document.getElementById('container');
// Функция, которая рисует элементы и выделяет индекс searchIndex
function drawElements(elements, searchIndex) {
container.innerHTML = ''; // Очищаем контейнер
elements.forEach((element, index) => {
const el = document.createElement('div');
el.className = `element${index === searchIndex ? ' highlight' : ''}`;
el.innerText = element;
container.appendChild(el);
});
}
// Функция бинарного поиска
function binarySearch(arr, target) {
let start = 0;
let end = arr.length - 1;
while (start <= end) {
const middle = Math.floor((start + end) / 2); // Находим середину
drawElements(arr, middle);
if (arr[middle] === target) {
return middle;
} else if (arr[middle] < target) {
start = middle + 1;
} else {
end = middle - 1;
}
}
return -1; // Если элемент не найден
}
// Тестовый массив и целевой элемент
const array = [10, 20, 30, 40, 50, 60, 70, 80, 90, 100];
const targetElement = 70;
const resultIndex = binarySearch(array, targetElement);
if (resultIndex !== -1) {
console.log(`Элемент ${targetElement} найден в индексе ${resultIndex}`);
} else {
console.log(`Элемент ${targetElement} не найден`);
}
В данном примере бинарный поиск будет визуализирован на странице в браузере. Элементы массива рисуются в виде квадратов, и выделяется индекс, который проверяется на каждой итерации. Результат поиска выводится в консоль браузера.