javascript 二分法(數組array)

來源:互聯網
上載者:User

在Javascript中,我們可以通過prototype關鍵字為對象添加新的屬性或者是方法,下面是一個為Array對象添加二分法尋找功能的方法: 複製代碼 代碼如下: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);
}
//如下為測試代碼:
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();
}

下面是國外的代碼
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 < 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;
}

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.