源码网商城,靠谱的源码在线交易网站 我的订单 购物车 帮助

源码网商城

javascript 折半查找字符在数组中的位置(有序列表)

  • 时间:2020-02-25 02:09 编辑: 来源: 阅读:
  • 扫一扫,手机访问
摘要:javascript 折半查找字符在数组中的位置(有序列表)
[u]复制代码[/u] 代码如下:
/** * 折半查找字符在数组中的位置(有序列表) * @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'));
  • 全部评论(0)
联系客服
客服电话:
400-000-3129
微信版

扫一扫进微信版
返回顶部