// import visualization libraries { const { Tracer, Array1DTracer, ChartTracer, LogTracer, Randomize, Layout, VerticalLayout } = require('algorithm-visualizer'); // } // define tracer variables { const chart = new ChartTracer(); const tracer = new Array1DTracer(); const logger = new LogTracer(); Layout.setRoot(new VerticalLayout([chart, tracer, logger])); const D = Randomize.Array1D({ N: 15, value: () => Randomize.Integer({ min: 0, max: 50 }), sorted: true }); tracer.set(D); tracer.chart(chart); Tracer.delay(); // } function BinarySearch(array, element) { // array = sorted array, element = element to be found let minIndex = 0; let maxIndex = array.length - 1; let testElement; while (minIndex <= maxIndex) { const middleIndex = Math.floor((minIndex + maxIndex) / 2); testElement = array[middleIndex]; // visualize { tracer.select(minIndex, maxIndex); Tracer.delay(); tracer.patch(middleIndex); logger.println(`Searching at index: ${middleIndex}`); Tracer.delay(); tracer.depatch(middleIndex); tracer.deselect(minIndex, maxIndex); // } if (testElement < element) { // logger { logger.println('Going right.'); // } minIndex = middleIndex + 1; } else if (testElement > element) { // logger { logger.println('Going left.'); // } maxIndex = middleIndex - 1; } else { // visualize { logger.println(`${element} is found at position ${middleIndex}!`); tracer.select(middleIndex); // } return middleIndex; } } // logger { logger.println(`${element} is not found!`); // } return -1; } const element = D[Randomize.Integer({ min: 0, max: D.length - 1 })]; // logger { logger.println(`Using iterative binary search to find ${element}`); // } BinarySearch(D, element);这是什么算法
时间: 2024-04-23 13:23:36 浏览: 81
基于java的论坛系统的开题报告.docx
这是二分查找算法的可视化实现。二分查找算法,也叫折半查找,是一种在有序数组中查找某一特定元素的搜索算法。它的时间复杂度为 O(log n),比线性查找更加高效。该算法采用分治法的思想,将查找区间不断缩小,直到找到目标元素或者查找区间为空。在每一次比较中,将查找区间对半分,判断目标元素在哪一半,然后将查找区间缩小到该半边,继续执行查找。上述代码使用可视化工具 Algorithm Visualizer 对该算法进行了可视化实现。
阅读全文