Home >Web Front-end >JS Tutorial >javascript dichotomy (array array)_javascript skills

javascript dichotomy (array array)_javascript skills

WBOY
WBOYOriginal
2016-05-16 18:28:541186browse

In Javascript, we can add new attributes or methods to objects through the prototype keyword. Here is a method to add a binary search function to an Array object:

Copy Code The code is as follows:

Array.prototype.binarySearch = function(obj)
{
var value = 0;
var left = 0;
var right= this.length;
while(left <= right)
{
var center = Math.floor((left right)/2);
if( this[center] == obj)
{
value = center;
}
if(obj < this[center])
{
right = center - 1;
}
else
{
left = center 1;
}
}
alert(value);
}
//The following is the test code:
function testArrayBinarySearch()
{
var array = new Array();
var key = 678;
var number = 1000;
for (i = 0; i < number ; i )
{
array.push(i);
}
array.binarySearch(key);
}
window.onload = function()
{
testArrayBinarySearch();
}

The following is the foreign code
javascript dichotomy//Copyright 2009 Nicholas C. Zakas. All rights reserved.
//MIT- Licensed, see source file
Copy code The code is as follows:

function binarySearch(items, value) {
var startIndex = 0,
stopIndex = items.length - 1,
middle = Math.floor((stopIndex startIndex)/2);
while(items[middle] != value && startIndex < stopIndex){
//adjust search area (adjust search area)
if (value < items[middle]){
stopIndex = middle - 1;
} else if (value > items[middle]){
startIndex = middle 1;
}
//recalculate middle (recalculate the middle item index)
middle = Math.floor((stopIndex startIndex)/2) ;
}
//make sure it's the right value (make sure to return the correct value)
return (items[middle] != value) ? -1 : middle;
}
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