Home > Web Front-end > JS Tutorial > body text

Javascript implements binary search method implementation code_javascript skills

WBOY
Release: 2016-05-16 19:07:56
Original
1062 people have browsed it

Generally, int[] type is used for binary classification... In js, it may be more flexibly used as a-z, or pinyin... or...

However, a question worth pondering is whether it is worthwhile to go through the following process in order to achieve binary search for pinyin and the like:

1. Sorting pinyin seems to require a lot of code.

2. Then do a binary search. This requires identifying the size of Pinyin, which seems not too small.

It’s fast to find results, but it’s much slower for others to download your js files. Haha, who should I abandon?

The following code can even have 1 billion entries, and it will still be found quickly, but use the iteration mode to create the array. . . So don’t try it. Just to give you an idea, I will post a JS solution to the Eight Queens problem next time. Haha, the algorithm is amazing


Copy code The code is as follows:

var array = [];
var key = 482;
var number = 1000;

for(i= 0;i array.push(i);
}
//-->>
var time = new Date();
var a ;
var left = 0;
var right= array.length;
while(left<=right){
var center=Math.floor((left right)/2);
if(array[center] == key) a = center;
if(key < array[center]){
right = center - 1;
}else{
left = center 1;
}
}
alert("Results of binary search:" a);
alert((new Date() - time)/1000);


source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template