javascript 二分法(数组array)_javascript技巧
程序员文章站
2022-04-25 15:21:14
...
在Javascript中,我们可以通过prototype关键字为对象添加新的属性或者是方法,下面是一个为Array对象添加二分法查找功能的方法:
Array.prototype.binarySearch = function(obj)
{
var value = 0;
var left = 0;
var right= this.length;
while(left {
var center = Math.floor((left+right)/2);
if(this[center] == obj)
{
value = center;
}
if(obj {
right = center - 1;
}
else
{
left = center + 1;
}
}
alert(value);
}
//如下为测试代码:
function testArrayBinarySearch()
{
var array = new Array();
var key = 678;
var number = 1000;
for (i = 0; i {
array.push(i);
}
array.binarySearch(key);
}
window.onload = function()
{
testArrayBinarySearch();
}
下面是国外的代码
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 = Math.floor((stopIndex + startIndex)/2);
while(items[middle] != value && startIndex //adjust search area(调整查找范围)
if (value stopIndex = middle - 1;
} else if (value > items[middle]){
startIndex = middle + 1;
}
//recalculate middle(重新计算中项索引)
middle = Math.floor((stopIndex + startIndex)/2);
}
//make sure it's the right value(确保返回正确的值)
return (items[middle] != value) ? -1 : middle;
}
复制代码 代码如下:
Array.prototype.binarySearch = function(obj)
{
var value = 0;
var left = 0;
var right= this.length;
while(left {
var center = Math.floor((left+right)/2);
if(this[center] == obj)
{
value = center;
}
if(obj {
right = center - 1;
}
else
{
left = center + 1;
}
}
alert(value);
}
//如下为测试代码:
function testArrayBinarySearch()
{
var array = new Array();
var key = 678;
var number = 1000;
for (i = 0; i {
array.push(i);
}
array.binarySearch(key);
}
window.onload = function()
{
testArrayBinarySearch();
}
下面是国外的代码
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 = Math.floor((stopIndex + startIndex)/2);
while(items[middle] != value && startIndex //adjust search area(调整查找范围)
if (value stopIndex = middle - 1;
} else if (value > items[middle]){
startIndex = middle + 1;
}
//recalculate middle(重新计算中项索引)
middle = Math.floor((stopIndex + startIndex)/2);
}
//make sure it's the right value(确保返回正确的值)
return (items[middle] != value) ? -1 : middle;
}
推荐阅读
-
window.event.keyCode兼容IE和Firefox实现js代码_javascript技巧
-
图片上传插件jquery.uploadify详解_javascript技巧
-
PHP数组传递给JavaScript以及json_encode的gbk中文乱码的解决_PHP教程
-
Google Map Api和GOOGLE Search Api整合实现代码_javascript技巧
-
javascript中scrollTop详解_javascript技巧
-
JavaScript可以减少代码量常用的12个技巧
-
js实现目录定位正文示例_javascript技巧
-
手机平板等移动端适配跳转URL的js代码_javascript技巧
-
javascript Array.sort() 跨浏览器下需要考虑的问题_javascript技巧
-
js form 验证函数 当前比较流行的错误提示_javascript技巧