本文實例講述了PHP快速排序算法。分享給大家供大家參考,具體如下:
快速排序:在無序的數(shù)組$data中,選擇任意一個值作為對比值,定義i為頭部檢索索引,j為尾部檢索索引,
算法步驟:
(1)初始化對比值$value=$data[0]
,$i=1
,$j=count($data)-1
(2)首先從尾部開始檢索,判斷$data[$j]
是否小于$value
,若不小于則$j--
,繼續(xù)檢索,直到找到比$value
小的坐標
(3)這時開始頭部檢索,判斷$data[$i]
是否大于$value
,若不大于則$i++
,繼續(xù)檢索,直到找到比$value
大的坐標
(4)這時$data[$j]
與$data[$i]
的值相互交換,即把比$value
大的放到右邊,把比$value
小的放到左邊
(5)重復3、4直到$i==$j
(6)這時已經(jīng)把比$value
大的放到右邊,把比$value
小的放到左邊,確定了中間的坐標位置為$i
,中間值為$value
,把$data[$i]
的值與$data[0]
的值交換,因為中間值為$value
,需要把$value
挪到數(shù)組的中間坐標
(7)數(shù)組分成左右2個無序的數(shù)組,再分別遞歸執(zhí)行1-6,直到數(shù)組長度為1
Tips:快速排序的中文定義百度下會更清楚
代碼:
?php header("Content-type: text/html; charset=utf-8"); function quickSort($data, $startIndex, $endIndex){ if($startIndex $endIndex){ $value = $data[$startIndex]; // 對比值 $startT = $startIndex + 1; $endT = $endIndex; while ($startT != $endT) { // 找到比對比值小的坐標 while ($data[$endT] > $value $endT > $startT){ $endT--; } // 找到比對比值大的左邊 while ($data[$startT] $value $startT $endT){ $startT++; } if($endT > $startT){ $temp =$data[$startT]; $data[$startT] = $data[$endT]; $data[$endT] = $temp; } } // 防止數(shù)組已經(jīng)排序好的情況 if($data[$startT] $value){ $data[$startIndex] = $data[$startT]; $data[$startT] = $value; } $data = quickSort($data, $startIndex, $startT - 1); $data = quickSort($data, $startT + 1, $endIndex); return $data; }else{ return $data; } } $data = array(10, 5, 30, 22, 1, 42, 14, 34, 8, 13, 28, 36, 7); $data = quickSort($data, 0, count($data) - 1); var_dump($data);
運行結(jié)果:
array(13) {
[0]=>
int(1)
[1]=>
int(5)
[2]=>
int(7)
[3]=>
int(8)
[4]=>
int(10)
[5]=>
int(13)
[6]=>
int(14)
[7]=>
int(22)
[8]=>
int(28)
[9]=>
int(30)
[10]=>
int(34)
[11]=>
int(36)
[12]=>
int(42)
}
PS:這里再為大家推薦一款關(guān)于排序的演示工具供大家參考:
在線動畫演示插入/選擇/冒泡/歸并/希爾/快速排序算法過程工具:
http://tools.jb51.net/aideddesign/paixu_ys
更多關(guān)于PHP相關(guān)內(nèi)容感興趣的讀者可查看本站專題:《php排序算法總結(jié)》、《PHP數(shù)據(jù)結(jié)構(gòu)與算法教程》、《php程序設(shè)計算法總結(jié)》、《php字符串(string)用法總結(jié)》、《PHP數(shù)組(Array)操作技巧大全》、《PHP常用遍歷算法與技巧總結(jié)》及《PHP數(shù)學運算技巧總結(jié)》
希望本文所述對大家PHP程序設(shè)計有所幫助。