public function actionQuick_sort($array)
{
// find array size
$length = count($array);
// base case test, if array of length 0 then just return array to caller
if($length <= 1)
{
return $array;
}
else
{
// select an item to act as our pivot point, since list is unsorted first position is easiest
$pivot = $array[0];
// declare our two arrays to act as partitions
$left = $right = array();
// loop and compare each item in the array to the pivot value, place item in appropriate partition
for($i = 1; $i < count($array); $i++)
{
if($array[$i] < $pivot)
{
$left[] = $array[$i];
}
else
{
$right[] = $array[$i];
}
}
// use recursion to now sort the left and right lists
return array_merge($this->actionQuick_sort($left), array($pivot), $this->actionQuick_sort($right));
}
}
public function actionTest()
{
// $arr = array(6,8,7,9,0,1,3,2,4,5);
// // print_r($arr);
// $this->actionQuicksort($arr,0,9);
// print_r($arr);
// $unsorted = array(43,21,2,1,9,24,2,99,23,8,7,114,92,5);
$unsorted = array(6,8,7,9,0,1,3,2,4,5);
$unsorted = array(10,2,36,14,10,25,23,85,99,45);
$sorted = $this->actionQuick_sort($unsorted);
print_r($sorted);
}
PHP实现快速排序
最新推荐文章于 2024-08-22 09:44:18 发布