复制代码 代码如下:
/**
* 折半查找字符在数组中的位置(有序列表)
* @param array 被检索的数组
* @param x 要查找的字符
* @type int
* @returns 字符在数组中的位置,没找到返回-1
*/
function binarySearch(array,x){
var lowPoint=1;
var higPoint=array.length;
var returnValue=-1;
var midPoint;
var found=false;
while ((lowPoint<=higPoint)&&(!found)){
midPoint=Math.ceil((lowPoint+higPoint)/2);
//console.log(lowPoint+"===="+midPoint+"===="+higPoint);
if(x>array[midPoint-1]){
lowPoint=midPoint+1;
}
else if(x<array[midPoint-1]){
higPoint= midPoint-1;
}
else if(x=array[midPoint-1]){
found=true;
}
}
if(found){
returnValue=midPoint;
}
return returnValue;
}
/*var array2=[1,2,3,4,5,6,7,8,9,100,109];*/
var array2=['a','b','c','d','e','f','g'];
console.log(binarySearch(array2,'c'));
您可能感兴趣的文章:
- JS查找数组中重复元素的方法详解
- 利用js查找数组中指定元素并返回该元素的所有索引示例
- 使用indexOf等在JavaScript的数组中进行元素查找和替换
- javascript实现查找数组中最大值方法汇总
- JavaScript使用二分查找算法在数组中查找数据的方法
- JavaScript实现在数组中查找不同顺序排列的字符串
- js中数组结合字符串实现查找(屏蔽广告判断url等)
- JS算法题之查找数字在数组中的索引位置
- JavaScript遍历查找数组中最大值与最小值的方法示例
- JS实现查找数组中对象的属性值是否存在示例