jQuery實現郵箱下拉列表自動補全功能
710
2024-02-19
本文實例講述了PHP實現的折半查詢算法。分享給大家供大家參考,具體如下:
什么是折半查詢算法?具體文字描述自己百度。直接上代碼:
<?php header("Content-type: text/html; charset=utf-8"); /* 折半查詢算法--不用遞歸 */ function qSort($data = array(), $x = 0){ $startIndex = 0; // 開始索引 $endIndex = count($data) - 1; // 結束索引 $index = 0; $number = 0; // 計數器 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; } /* 折半查詢算法--使用遞歸 */ 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 '結果:'.$index;
運行結果:
更多關于PHP相關內容感興趣的讀者可查看本站專題:《PHP數據結構與算法教程》、《PHP基本語法入門教程》、《php面向對象程序設計入門教程》、《php字符串(string)用法總結》及《php程序設計算法總結》
希望本文所述對大家PHP程序設計有所幫助。
#免責聲明#
本站[綠夏技術導航]提供的一切軟件、教程和內容信息僅限用于學習和研究目的;不得將上述內容用于商業或者非法用途,否則,一切后果請用戶自負。本站信息來自網絡收集整理,版權爭議與本站無關。您必須在下載后的24個小時之內,從您的電腦或手機中徹底刪除上述內容。如果您喜歡該程序或內容,請支持正版,購買注冊,得到更好的正版服務。我們非常重視版權問題,如有侵權請郵件[admin@lxwl520.com]與我們聯系進行刪除處理。敬請諒解!