好吧,我承认最近我跟快速排序干上了,各种测试编写快速排序程序,现在就用php实现快速排序,跟之前文章不同,这次php的快排是能解决实际需要的.下面的文章里我会用c语言的思想提出两种php快速排序的解决方案:
$array = array ( array ( 'name' => "xiao", 'age' => 3 ), array ( 'name' => 'wang', 'age' => 1 ), array ( 'name' => 'chen', 'age' => 2 ) );
/** * 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); } }
<?php $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; }
/** * Description:类似于c中qsort的比较函数 * * @param array $a * @param array $b * @param string $field * @return int */ function compare ($a, $b) { return $a['age'] - $b['age']; } usort($array, "compare");
<?php $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(); usort($array, "compare"); print_r($array); $end = getTime(); $spend = $end - $begin; echo "花费时间为:" . $spend . "秒\n"; function getTime () { list ($msec, $sec) = explode(" ", microtime()); return (float) $msec + (float) $sec; }