本文實(shí)例講述了PHP基于二分法實(shí)現(xiàn)數(shù)組查找功能。分享給大家供大家參考,具體如下:
二分法。分別使用while循環(huán)的方法和遞歸調(diào)用的方法。
?php // 二分法的使用數(shù)組必須是有序的,或升序,或降序 $arr = array( 1, 3, 5, 7, 9, 13 ); // 遞歸調(diào)用(相比較好理解 function bsearch_r($v, $arr, $low, $high){ if ($low > $high) {// 先判斷結(jié)束條件 return -1; } $i = intval(($high + $low)/2); if ($arr[$i] > $v){ return bsearch_r($v, $arr, $low, $i-1);// 遞歸 } else if ($arr[$i] $v){ return bsearch_r($v, $arr, $i+1, $high); } else { return $i; } } echo bsearch_r(1, $arr, 0, count($arr)-1);// 0 echo 'hr/>'; echo bsearch_r(14, $arr, 0, count($arr)-1);// -1 echo 'hr/>'; // while循環(huán) function bsearch($v, $arr){ $low = 0; $high = count($arr)-1;// 使用下標(biāo),注意減去1 // 注意凡是使用到while的時(shí)候,一定要防備無限循環(huán)的時(shí)候,注意終止循環(huán)的判斷。 while($low = $high){// 比如$low=$high,這個(gè)等于號(hào)必須有。 $i = intval(($high + $low)/2); if ($arr[$i] > $v){ $high = $i-1; } else if ($arr[$i] $v){ $low = $i+1; } else { return $i; } } return -1;// 找不到的時(shí)候返回-1 } echo bsearch(13, $arr);// 5 echo 'hr/>'; echo bsearch(14, $arr);// -1
運(yùn)行結(jié)果:
更多關(guān)于PHP相關(guān)內(nèi)容感興趣的讀者可查看本站專題:《PHP數(shù)據(jù)結(jié)構(gòu)與算法教程》、《php程序設(shè)計(jì)算法總結(jié)》、《php字符串(string)用法總結(jié)》、《PHP數(shù)組(Array)操作技巧大全》、《PHP常用遍歷算法與技巧總結(jié)》及《PHP數(shù)學(xué)運(yùn)算技巧總結(jié)》
希望本文所述對(duì)大家PHP程序設(shè)計(jì)有所幫助。
標(biāo)簽:樂山 六安 十堰 定西 佛山 迪慶 海南 南寧
巨人網(wǎng)絡(luò)通訊聲明:本文標(biāo)題《PHP基于二分法實(shí)現(xiàn)數(shù)組查找功能示例【循環(huán)與遞歸算法】》,本文關(guān)鍵詞 PHP,基于,二,分法,實(shí)現(xiàn),數(shù)組,;如發(fā)現(xiàn)本文內(nèi)容存在版權(quán)問題,煩請(qǐng)?zhí)峁┫嚓P(guān)信息告之我們,我們將及時(shí)溝通與處理。本站內(nèi)容系統(tǒng)采集于網(wǎng)絡(luò),涉及言論、版權(quán)與本站無關(guān)。