搜索算法有以下两种。
const linearSearch = (arr, value) => { for (let item of arr) { if (item == value) { return true; } } return false; }; console.log(linearSearch([1,2,3,4,5,6,7,8,9], 7)); console.log(linearSearch([1,2,3,4,5,6,7,8,9], 3)); console.log(linearSearch([1,2,3,4,5,6,7,8,9], 10)); console.log(linearSearch([1,2,3,4,5,6,7,8,9], 9));
二分查找
const binarySearch = (arr, value, low = 0, high=arr.length-1) => { const mid = Math.floor((low high)/2); const midValue = arr[mid]; if (low > high) { return false; } if (midValue == value) { return true; } else if (midValue > value) { return binarySearch(arr, value, low, mid); } else { return binarySearch(arr, value, mid 1, high); } } const arr = [9,8,7,6,5,4,3,2,1]; arr.sort((a,b) => a-b); console.log(binarySearch(arr, 7)); console.log(binarySearch(arr, 3)); console.log(binarySearch(arr, 10)); console.log(binarySearch(arr, 9));
免责声明: 提供的所有资源部分来自互联网,如果有侵犯您的版权或其他权益,请说明详细缘由并提供版权或权益证明然后发到邮箱:[email protected] 我们会第一时间内为您处理。
Copyright© 2022 湘ICP备2022001581号-3