php實現折半查詢演算法的方法分享

來源:互聯網
上載者:User
這篇文章主要介紹了PHP實現的折半查詢演算法,結合完整執行個體形式分析了php使用遞迴與非遞迴實現折半查詢的演算法操作步驟與使用方法,需要的朋友可以參考下

本文執行個體講述了PHP實現的折半查詢演算法。分享給大家供大家參考,具體如下:

什麼是折半查詢演算法?具體文字描述自己百度。直接上代碼:


<?phpheader("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;

運行結果:

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.