/* 二分查找(折半查找) 思路: low和high表示下标,选择每个数组的中点作为基准,比较基准与key的值, 若大于基准,则移动low,反之移动high,等于则返回该值,不存在返回-1 遇到的问题:写成了死循环,无返回值 */ var arr = [1,4,5,7,3,9,8]; var ff = binarySearch(arr,4); console.log(ff); function binarySearch(arr,key) { var low = 0; var high = arr.length-1; while(low<=high){ var mid =Math.floor( (high+low)/2); if(arr[mid]==key){ return arr[mid]; } if (key<arr[mid]) { high = mid; }else if(key>arr[mid]){ low = mid; }else{ return mid; } } return -1; }
时间: 2024-11-06 20:48:13