日期:2014-05-16  浏览次数:20287 次

JS二分查找(预排序数组的查找)

js二分查找数据,数据首先要经过排序。

二分查找可以解决(预排序数组的查找)问题:只要数组中包含value(即要查找的值),
?那么通过不断缩小包含value的范围,最终就可以找到它,找不到返回-1。

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="zh-CN" dir="ltr">
	<head>
<meta http-equiv="Content-Type" content="text/html; charset=GBK"/>
		<script type="text/javascript">
			
//Copyright 2009 Nicholas C. Zakas. All rights reserved. 
//MIT-Licensed, see source file 
function binarySearch(items, value){ 
    var startIndex  = 0;
    stopIndex = items.length - 1;
    middle = (stopIndex + startIndex)>>>1;
    while(items[middle] != value && startIndex < stopIndex){ 
  
        //adjust search area(调整查找范围) 
        if (value < items[middle]){ 
            stopIndex = middle - 1; 
        } else if (value > items[middle]){ 
            startIndex = middle + 1; 
        } 
  
        //recalculate middle(重新计算中项索引) 
	 middle = (stopIndex + startIndex)>>>1;
    } 
  
    //make sure it's the right value(确保返回正确的值) 
    return (items[middle] != value) ? -1 : middle; 
} 

function test(){
	var arr = [0,1,2,3,4,5,6,7,8,9,10,11,12];
	var rv=binarySearch(arr,5);
	alert(rv);
}
		</script>
	</head>
	<body>
		<a href="javascript:test();">search</a>
	</body>
</html>

?