快速排序算法的PHP實現:
function quickSort($arr){
$length = count($arr);
if($length <= 1){
return $arr;
}
$pivot = $arr[0];
$left = [];
$right = [];
for($i=1; $i<$length; $i++){
if($arr[$i] < $pivot){
$left[] = $arr[$i];
}else{
$right[] = $arr[$i];
}
}
return array_merge(quickSort($left), [$pivot], quickSort($right));
}
$arr = [3, 6, 8, 10, 1, 2, 1];
$sortedArr = quickSort($arr);
print_r($sortedArr);
歸并排序算法的PHP實現:
function mergeSort($arr){
$length = count($arr);
if($length <= 1){
return $arr;
}
$mid = (int)($length / 2);
$left = array_slice($arr, 0, $mid);
$right = array_slice($arr, $mid);
$left = mergeSort($left);
$right = mergeSort($right);
return merge($left, $right);
}
function merge($left, $right){
$result = [];
while(count($left) > 0 && count($right) > 0){
if($left[0] < $right[0]){
array_push($result, array_shift($left));
}else{
array_push($result, array_shift($right));
}
}
while(count($left) > 0){
array_push($result, array_shift($left));
}
while(count($right) > 0){
array_push($result, array_shift($right));
}
return $result;
}
$arr = [3, 6, 8, 10, 1, 2, 1];
$sortedArr = mergeSort($arr);
print_r($sortedArr);