php 快速排序演算法,php 快速排序函式

2021-10-25 22:36:55 字數 2642 閱讀 6167

在php程式設計中會用到一些常用的演算法,把這些演算法**寫成函式方便以後呼叫^_^。php快速排序函式就這樣誕生了,兩個版本,遞迴和無遞迴。可以根據實際需要選用。

* qsort 資料快速排序遞迴版

* $array_to_sort 需要排序的陣列

* 排序過程中,陣列的鍵會被替換為數字索引的鍵

* 如果$array_to_sort不是陣列返回false

* 排序成功返回true

* $lvl為遞迴深度

function qsort( &$array_to_sort, $btm=null, $top=null, $lvl=0 )

// check if top of recursion and do checks

// otherwise the checks slow down the recursion

if ( $lvl == 0 )

if ( !is_array($array_to_sort) )

// yank all the values out to prevent incorrect keying

$array_to_sort = array_values($array_to_sort);

$btm=0;

$top=count($array_to_sort)-1;

$lo = $btm;

$hi = $top;

$pivot = $array_to_sort[$hi];

// throw highs and lows to each side of the element

// and the one element will be in the correct position,

// then array is already partially sorted

while ( $lo < $hi )

while ( $lo < $hi && $pivot > strval($array_to_sort[$lo]) )

if ( $lo != $hi )

while ( $lo < $hi && strval($array_to_sort[$hi]) > $pivot )

if ( $lo != $hi )

// now $lo and $hi are on the sorted element

if ( $lo-1 > $btm ) // if equal, there is only one sorted element

if ( $top > $lo+1 ) // see last comment

return true;

/* author: jblamer, date: 20070322

* qsort0 陣列快速排序非遞迴版

* 引數用法同上

function qsort0( &$array_to_sort )

if ( !is_array($array_to_sort) )

// yank all the values out to prevent incorrect keying

$array_to_sort = array_values($array_to_sort);

// record where we are via stack

$track_sort = array();

array_push($track_sort, array(0, count($array_to_sort)-1));

while ( count($track_sort) > 0 )

$hold = array_pop($track_sort);

$lo = $hold[0];

$hi = $hold[1];

$pivot = $array_to_sort[$hi];

// throw highs and lows to each side of the element

// and the one element will be in the correct position,

// then array is already partially sorted

while ( $lo < $hi )

while ( $lo < $hi && $pivot > strval($array_to_sort[$lo]) )

if ( $lo != $hi )

while ( $lo < $hi && strval($array_to_sort[$hi]) > $pivot )

if ( $lo != $hi )

// now $lo and $hi are on the sorted element

if ( $lo-1 > $hold[0] ) // if equal, there is only one sorted element

if ( $hold[1] > $lo+1 ) // see last comment

return true;

// this function is to swap element a with b

if ( !function_exists('swap') )

function swap( &$a, &$b )

$h = $a;

$a = $b;

$b = $h;

php 快速排序演算法,PHP 快速排序演算法

概念 快速排序演算法是對冒泡演算法的乙個優化。他的思想是先對陣列進行分割,把大的元素數值放到乙個臨時陣列裡,把小的元素數值放到另乙個臨時陣列裡 這個分割的點可以是陣列中的任意乙個元素值,一般用第乙個元素,即 array 0 然後繼續把這兩個臨時陣列重複上面拆分,最後把小的陣列元素和大的陣列元素合併起...

PHP快速排序演算法

看了c語言版本的快速排序後,我用php實現了一遍。難度在於在乙個陣列上面進行位置的交換理解 一列很長很長很長的隊伍,我要排序,先抽乙個隊長,然後以隊長為準,比隊長高的排隊長右邊,比隊長矮的排隊長左邊。然後以隊長為中界分成兩個小分隊。各小分隊又抽乙個小隊長 這個小隊長又按照大隊長的做法做了一遍 取第乙...

PHP快速排序演算法

快速排序使用分治策略來把待排序資料序列分為兩個子串行,具體步驟為 1 從數列中挑出乙個元素,稱該元素為 基準 2 掃瞄一遍數列,將所有比 基準 小的元素排在基準前面,所有比 基準 大的元素排在基準後面。3 通過遞迴,將各子串行劃分為更小的序列,直到把小於基準值元素的子數列和大於基準值元素的子數列排序...