/**
* 简单式快排,空间复杂度更高
* @param type $arr
* @return type
*/
public function quickSortSimple($arr)
{
$length = count($arr);
if ($length == 1 || $length == 0)
{
return $arr;
}
$left_arr = [];
$right_arr = [];
$flag = $arr[0];
//循环时不要拿flag比较
for ($i = 1; $i < $length; $i++)
{
$value = $arr[$i];
if ($value <= $flag)
{
$left_arr[] = $value;
}
else
{
$right_arr[] = $value;
}
}
return array_merge($this->quickSortSimple($left_arr), [ $flag ], $this->quickSortSimple($right_arr));
}
/**
* 快排分堆,返回中轴坐标
* @param type $arr
* @param type $left_index
* @param type $right_index
* @return type
*/
public function quickSortPivot(&$arr, $left_index = 0, $right_index = 0)
{
$flag = $arr[$left_index];
while ($right_index > $left_index)
{
//这里是大于等于
if ($right_index > $left_index && $arr[$right_index] >= $flag)
{
$right_index--;
}
$this->swap($arr, $left_index, $right_index);
//这里是大于等于
if ($right_index > $left_index && $arr[$left_index] <= $flag)
{
$left_index++;
}
$this->swap($arr, $left_index, $right_index);
}
//不要忘记返回pivot
return $left_index;
}
/**
* 交换数组的值
* @param array $arr
* @param type $index_a
* @param type $index_b
*/
public function swap(array &$arr, $index_a, $index_b)
{
$temp = $arr[$index_a];
$arr[$index_a] = $arr[$index_b];
$arr[$index_b] = $temp;
}
/**
* index版本的快排
* @param array $arr
* @param type $low
* @param type $high
*/
public function quickSortIndex(array &$arr, $low, $high)
{
if ($low < $high)
{
$pivot = $this->quickSortPivot($arr, $low, $high);
$this->quickSortIndex($arr, $low, $pivot - 1);
$this->quickSortIndex($arr, $pivot + 1, $high);
}
}
/**
* 冒泡排序
* @param type $arr
* @return type
*/
public function bubble($arr)
{
$length = count($arr);
//大于等于0,从后往前,注意是--
for ($i = $length - 1; $i >= 1; $i--)
{
//小于等于$i-1 别写成了$length-1
for ($j = 0; $j <= $i-1; $j++)
{
if ($arr[$j] > $arr[$j + 1])
{
$this->swap($arr, $j, $j + 1);
}
}
}
return $arr;
}
php排序算法
猜你喜欢
转载自blog.csdn.net/u012993454/article/details/81868605
今日推荐
周排行