企业🤖AI智能体构建引擎,智能编排和调试,一键部署,支持私有化部署方案 广告
[TOC] # Binary Search Algorithm ``` // 来自 https://www.cnblogs.com/Answer1215/category/534566.html // 使用 TypeScript function binarySearch ( array: number[], element: number, start: number = 0, end: number = array.length - 1 ):number { if(end < start) return -1; const middle = Math.floor((start + end) /2); return element === array[middle] ? middle : element < array[middle] ? binarySearch(array, element, start, middle -1) : binarySearch(array, element, middle + 1, end); } const unsortedArray = [6, 7, 8, 9, 10, 1, 2, 3, 4, 5] console.log("12312312: ", unsortedArray.sort()) // 注意这里的 sort 的结果:[1, 10, 2, 3, 4, 5, 6, 7, 8, 9] console.log("index of 4: ", binarySearch(unsortedArray.sort(), 4)) console.log("22 not found: ", binarySearch(unsortedArray.sort(), 22)) ```