需求:求一个数字类型,在一个数组中的区间;
1 $(function(){ 2 //二分法计算最近的数组下标 3 Array.prototype.binarySearch = function(obj){ 4 //var value = 0; 5 var left = 0; 6 var right = this.length; 7 while(left <= right){ 8 var center = Math.floor((left+right)/2); 9 if(obj<this[center]){ 10 right = center - 1; 11 }else{ 12 left = center + 1; 13 } 14 } 15 return right; 16 } 17 //测试数据 18 var tempArray = new Array(‘0‘,‘10‘,‘20‘,‘30‘); 19 var obj = 18; 20 console(tempArray.binarySearch(obj)); 21 });
时间: 2024-10-07 12:12:49