PHP一個簡單的快速排序

eg756 9年前發布 | 845 次閱讀 PHP

通過不斷的定位基準數的位置來實現快速排序

<?php
/**

  • Created by PhpStorm.
  • User: saint
  • Date: 15/8/5
  • Time: 上午11:49 */ class Demo { public $a = array(3, 6, 9, 2, 4, 7, 1, 5, 8, 0);

    public function qsort($left, $right) {

     if($left > $right) {
         return;
     }
    
     $i = $left;
     $j = $right;
     $standard = $this->a[$left];
    
     while($i != $j) {
    
         // 從右向左查找比基準數小的單元
         while(($standard <= $this->a[$j]) && ($j > $i)) {
             $j--;
         }
    
         // 從左到右查找比基準數大的
         while(($standard >= $this->a[$i]) && ($j > $i)) {
             $i++;
         }
    
         $tmp = $this->a[$i];
         $this->a[$i] = $this->a[$j];
         $this->a[$j] = $tmp;
     }
    
     // 確定基準數的位置
     $this->a[$left] = $this->a[$i];
     $this->a[$i] = $standard;
    
     $this->qsort($left, $i - 1);
     $this->qsort($i + 1, $right);
    

    }

    // 執行函數 public function main() {

     $left = 0;
     $right = count($this->a) - 1;
     $this->qsort($left, $right);
     print_r($this->a);
    

    } }

$demo = new Demo(); $demo->main();</pre>
來自:http://my.oschina.net/liuke1556/blog/488215

 本文由用戶 eg756 自行上傳分享,僅供網友學習交流。所有權歸原作者,若您的權利被侵害,請聯系管理員。
 轉載本站原創文章,請注明出處,并保留原始鏈接、圖片水印。
 本站是一個以用戶分享為主的開源技術平臺,歡迎各類分享!