PHP實現快速排序演算法

來源:互聯網
上載者:User

快速排序(Quick Sort)是對冒泡排序的一種改進,屬不穩定排序演算法,由東尼·霍爾在1962年提出。快速排序基本步驟:從數列中挑出一個元素(一般稱為稱為“基準”),通過一趟排序將要排序的資料分割成獨立的兩部分,其中一部分的所有資料都比基準小,另外一部分的所有資料都比基準大,與基準相等的資料可放在兩部分中的任一部分,然後再按此方法遞迴地對這兩部分資料分別進行處理,以達到整個資料變成有序序列。快速排序,最好情況下,時間複雜度為O(nlogn);最壞情況下,時間複雜度為O(n2);平均時間複雜度為O(nlogn)。

快速排序樣本圖:

PHP實現快速排序演算法
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104 <?php/** * 資料結構與演算法(PHP實現) - 快速排序(Quick Sort)。 *
 * @author 創想編程(TOPPHP.ORG) * @copyright Copyright (c) 2013 創想編程(TOPPHP.ORG) All Rights Reserved * @license http://www.opensource.org/licenses/mit-license.php MIT LICENSE * @version 1.0.0 - Build20130614 */class
QuickSort {
  /**   * 需要排序的資料數組。   *
   * @var array   */  private
$data;   /**   * 資料數組的長度。   *
   * @var integer   */  private
$size;   /**   * 資料數組是否已排序。   *
   * @var boolean   */  private
$done;   /**   * 構造方法 - 初始化資料。   *
   * @param array $data 需要排序的資料數組。   */  public
function __construct(array
$data) {    $this->data =
$data;    $this->size =
count($this->data);    $this->done = FALSE;  }   /**   * 交換資料數組中兩個元素的位置。   *
   * @param integer $x 元素在數組中的索引。   * @param integer $y 元素在數組中的索引。   */  private
function swap($x,
$y) {    $temp
= $this->data[$x];    $this->data[$x] =
$this->data[$y];    $this->data[$y] =
$temp;  }   /**   * 快速排序。   *
   * @param integer $left 數組第一個元素索引。   * @param integer $right 數組最後一個元素索引。   */  private
function sort($left,
$right) {    if
($left
>=
$right) {      return
;    }     $pivot
= $this->data[$left];    $start
= $left;    $end
= $right;     while
($start
<
$end) {      while
($start
<
$end &&
$this->data[$end] >=
$pivot) {        --$end;      }       $this->swap($start,
$end);       while
($start
<
$end &&
$this->data[$start] <
$pivot) {        ++$start;      }       $this->swap($start,
$end);    }     $this->sort($left,
$start - 1);    $this->sort($start
+ 1, $right);  }   /**   * 擷取排序後的資料數組。   *
   * @return array 返回排序後的資料數組。   */  public
function getResult() {    if
($this->done) {      return
$this->data;    }     $this->sort(0,
$this->size - 1);    $this->done = TRUE;     return
$this->data;  }}?>
範例程式碼
1234 <?php$quick
=
new QuickSort(array(5, 3, 8, 9, 6, 2));echo
'<pre>'
, print_r($quick->getResult(), TRUE),
'</pre>';?>

聯繫我們

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