/**
* Description:获取中枢点的位置
*
* @param array $array
* @param int $left
* @param int $right
* @param string $field
* @return int
*/
function fetchArrayPivot (&$array, $left, $right, $field)
{
// 基准定义
$stand = $array[$left];
// 遍历数组
while ($left < $right) {
while ($left < $right && $array[$right][$field] >= $stand[$field]) {
$right --;
}
if ($left < $right) {
$array[$left ++] = $array[$right];
}
while ($left < $right && $array[$left][$field] <= $stand[$field]) {
$left ++;
}
if ($left < $right) {
$array[$right --] = $array[$left];
}
}
// 获取中枢点位置
$array[$left] = $stand;
return $left;
}
/**
* Description:快速排序主程序
*
* @param array $array
* @param int $begin
* @param int $end
* @param string $field
*/
function quickSort (&$array, $begin, $end, $field)
{
// 变量定义
$pivot = null;
if ($begin < $end) {
$pivot = fetchArrayPivot($array, $begin, $end, $field);
quickSort($array, $begin, $pivot - 1, $field);
quickSort($array, $pivot + 1, $end, $field);
}
}
2,调用示例:
$array = array(
array(
'name' => "xiao",
'age' => 3
),
array(
'name' => 'wang',
'age' => 1
),
array(
'name' => 'chen',
'age' => 2
),
array(
'name' => 'zhengyi',
'age' => 4
),
array(
'name' => 'chai',
'age' => 14
)
);
$begin = getTime();
quickSort($array, 0, count($array) - 1, 'age');
print_r($array);
$end = getTime();
$spend = $end - $begin;
echo "花费时间为:".$spend."秒n";
function getTime()
{
list($msec, $sec) = explode(" ", microtime());
return (float)$msec + (float)$sec;
}
|