本文實(shí)例講述了PHP實(shí)現(xiàn)的折半查詢(xún)算法。分享給大家供大家參考,具體如下:
什么是折半查詢(xún)算法?具體文字描述自己百度。直接上代碼:
<?php header("Content-type: text/html; charset=utf-8"); /* 折半查詢(xún)算法--不用遞歸 */ function qSort($data = array(), $x = 0){ $startIndex = 0; // 開(kāi)始索引 $endIndex = count($data) - 1; // 結(jié)束索引 $index = 0; $number = 0; // 計(jì)數(shù)器 do{ if($endIndex > $startIndex){ $searchIndex = ceil(($endIndex - $startIndex) / 2); }else if($endIndex == $startIndex){ $searchIndex = $endIndex; }else{ $index = -1; break; } $searchIndex += ($startIndex - 1); echo '檢索范圍:'.$startIndex.' ~ '.$endIndex.'<br>檢索位置:'.$searchIndex.'檢索值為:'.$data[$searchIndex]; echo '<br>=======================<br><br>'; if($data[$searchIndex] == $x){ $index = $searchIndex; break; }else if($x > $data[$searchIndex]){ $startIndex = $searchIndex + 1; }else{ $endIndex = $searchIndex - 1; } $number++; }while($number < count($data)); return $index; } /* 折半查詢(xún)算法--使用遞歸 */ function sSort($data, $x, $startIndex, $endIndex){ if($endIndex > $startIndex){ $searchIndex = ceil(($endIndex - $startIndex) / 2); }else if($endIndex == $startIndex){ $searchIndex = $endIndex; }else{ return -1; } $searchIndex += ($startIndex - 1); echo '檢索范圍:'.$startIndex.' ~ '.$endIndex.'<br>檢索位置:'.$searchIndex.'檢索值為:'.$data[$searchIndex]; echo '<br>=======================<br><br>'; if($data[$searchIndex] == $x){ return $searchIndex; }else if($x > $data[$searchIndex]){ $startIndex = $searchIndex + 1; return sSort($data, $x, $startIndex, $endIndex); }else{ $endIndex = $searchIndex - 1; return sSort($data, $x, $startIndex, $endIndex); } } $data = array(1, 3, 4, 6, 9, 11, 12, 13, 15, 20, 21, 25, 33, 34, 35, 39, 41, 44); $index = qSort($data, 11); // 不用遞歸的排序方法 $index = sSort($data, 11, 0, count($data) - 1); // 使用遞歸的排序方法 echo '結(jié)果:'.$index;
運(yùn)行結(jié)果:
更多關(guān)于PHP相關(guān)內(nèi)容感興趣的讀者可查看本站專(zhuān)題:《PHP數(shù)據(jù)結(jié)構(gòu)與算法教程》、《PHP基本語(yǔ)法入門(mén)教程》、《php面向?qū)ο蟪绦蛟O(shè)計(jì)入門(mén)教程》、《php字符串(string)用法總結(jié)》及《php程序設(shè)計(jì)算法總結(jié)》
希望本文所述對(duì)大家PHP程序設(shè)計(jì)有所幫助。
【網(wǎng)站聲明】本站除付費(fèi)源碼經(jīng)過(guò)測(cè)試外,其他素材未做測(cè)試,不保證完整性,網(wǎng)站上部分源碼僅限學(xué)習(xí)交流,請(qǐng)勿用于商業(yè)用途。如損害你的權(quán)益請(qǐng)聯(lián)系客服QQ:2655101040 給予處理,謝謝支持。