php常见排序

public function actionQuickSort()
{
$arr = ['5', '4', '3', '2', '1', '0'];
$quickRes = $this->quickSortInner($arr);
$selectRes = $this->selectSort($arr);
$insertRes = $this->insertSort($arr);
var_dump($insertRes);
}

private function quickSortInner($arr)
{
if(!is_array($arr)){
return false;
}
$length = count($arr);
if($length <= 1){
return $arr;//快速排序的出口 判断数组的长度
}
$left = array(); //左数组
$right = array(); //右数组
for($i = 0;$i < $length;$i++){
if($arr[$i] < $arr[0]){
$left[] = $arr[$i];
}else{
$right[] = $arr[$i];
}
}
$left = $this->quickSortInner($left);
$right = $this->quickSortInner($right);
return array_merge($left, $right);
}

private function selectSort($arr)
{
if(!is_array($arr)){
return false;
} $length = count($arr); if($length < 1){ return false; } for($i = 0;$i < $length;$i++){ $m = $i; for($j=$i+1;$j<$length;$j++){ if($arr[$m]>$arr[$j]){ $m=$j; } } if($arr[$i] != $arr[$m]){ $tmp = $arr[$m]; $arr[$m] = $arr[$i]; $arr[$i] = $tmp; } } return $arr;}public function insertSort($arr){ if(!is_array($arr)){ return false; } $length = count($arr); if($length < 1){ return $arr; } for($i = 1;$i<$length;$i++){ $tmp = $arr[$i]; for($j=$i-1;$j>0; $j--){ if($arr[$j]>$tmp){ $arr[$j+1] = $arr[$j] $arr[$j] = $tmp; }else{ break; }; } } return $arr;}
原文地址:https://www.cnblogs.com/jasonxiaoqinde/p/7682667.html