Home >Web Front-end >JS Tutorial >javascript Find the position of a character in an array by half (ordered list)_javascript skills

javascript Find the position of a character in an array by half (ordered list)_javascript skills

WBOY
WBOYOriginal
2016-05-16 18:14:161648browse
复制代码 代码如下:

/**
* Find the position of the character in the array (ordered list)
* @param array The retrieved array
* @param x The character to be found
* @type int
* @returns The position of the character in the array. If not found, return -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(xhigPoint= 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'));
Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn