快速排序算法那思想:气泡排序的一种改进,基本思路是每进行一趟遍历,将序列分割成两个独立的有序的部分,其实就是将整个序列看成两个气泡。在对含有n个元素的数组S的一次快速排序过程中,设置low=0,height=n-1,已S[0]为给定值并赋值给t,从height开始向左遍历并且height自减,找到第一个小于t的数据元素S[height],然后S[low]=S[height],再从low开始向右遍历并且low自加,找到第一个大于t的数据元素S[low],然后S[height]=S[low],知道low=height为止时,最后将t赋值给S[low]或S[height]一次快速排序结束。
代码实现:
/**
* @name 数组排序
* @use 使用快速排序算法对数组进行排序,数组类型为每个元素都含有“value”属性用于排序
* @param $height 指向排序段上边界
* @param $low 指向排序段下边界
* @param $arr 待排序数组
* @return $arr
*/
public static function quickSort($height, $low, &$arr)
{
$randNum = rand($low, $height);
$temp = $arr[$low];
$arr[$low] = $arr[$randNum];
$arr[$randNum] = $temp;
$lowTemp = $low;
$heightTemp = $height;
$initNum = $arr[$low];
$index = $low;
$switch = true;//true为从高位向地位找,false为从低位向高位找
while ($low != $height) {
if ($switch) {
if ($arr[$height]['value'] > $initNum['value']) {
$arr[$index] = $arr[$height];
$index = $height;
$switch = false;
}
$height--;
} else {
if ($arr[$low]['value'] < $initNum['value']) {
$arr[$index] = $arr[$low];
$index = $low;
$switch = true;
}
$low++;
}
}
$arr[$index] = $initNum;
if ($lowTemp < $index - 1) {
self::quickSort($index - 1, $lowTemp, $arr);
}
if ($heightTemp > $index + 1) {
self::quickSort($heightTemp, $index + 1, $arr);
}
}