快速排序(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>';?> |