Javascript的二分查找(预排序数组的查找)
《JavaScript高级程序设计》的作者Nicholas C. Zakas使用JavaScript实现的一些基本算法,链接地址如下http://www.nczonline.net/blog/tag/computer-science/。 其中,对本文提到的二分查找算法的实现如下:
- //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 < stopIndex){
- //adjust search area(调整查找范围)
- if (value < items[middle]){
- 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;
- }
Posted in javascript by waiwai at April 24th, 2010.
Hey, i think you visited my website so here i am!.I am looking for ways to add things to my website!I suppose its ok to use some of your ideas!!
[Reply]