gpt-3.5-turbo-0613· openai
Suzhen/CodeChat
Как реализовать на JS, бин поиск, чтобы была страница в брвузере, где видно, где…
- User
Как реализовать на JS, бин поиск, чтобы была страница в брвузере, где видно, где пробегают индексы? Визуализация алгоритма
- Assistant
Для визуализации алгоритма бинарного поиска на странице в браузере, можно воспользоваться JavaScript и HTML/CSS.
Вот пример реализации:
HTML:
<!DOCTYPE html> <html> <head> <title>Binary Search Visualization</title> <style> #container { margin-top: 50px; display: flex; justify-content: center; } .element { width: 20px; height: 20px; background-color: gray; display: flex; align-items: center; justify-content: center; margin-right: 5px; } .highlight { background-color: red; color: white; font-weight: bold; } </style> </head> <body> <h1>Binary Search Visualization</h1> <div id="container"></div> <script src="binarySearch.js"></script> </body> </html>JavaScript (binarySearch.js):
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} не найден`); }В данном примере бинарный поиск будет визуализирован на странице в браузере. Элементы массива рисуются в виде квадратов, и выделяется индекс, который проверяется на каждой итерации. Результат поиска выводится в консоль браузера.
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.