以下是一个使用PHP实现的快速排序算法的实例,包括迭代和递归两种方式。
迭代快排
```php

function quickSortIterative($array) {
$size = count($array);
$stack = new SplStack();
$stack->push(0);
$stack->push($size - 1);
while (!$stack->isEmpty()) {
$end = $stack->pop();
$start = $stack->pop();
$pivotIndex = partition($array, $start, $end);
if ($pivotIndex - 1 > $start) {
$stack->push($start);
$stack->push($pivotIndex - 1);
}
if ($pivotIndex + 1 < $end) {
$stack->push($pivotIndex + 1);
$stack->push($end);
}
}
return $array;
}
function partition($array, $start, $end) {
$pivot = $array[$end];
$i = $start - 1;
for ($j = $start; $j < $end; $j++) {
if ($array[$j] < $pivot) {
$i++;
swap($array, $i, $j);
}
}
swap($array, $i + 1, $end);
return $i + 1;
}
function swap(&$array, $i, $j) {
$temp = $array[$i];
$array[$i] = $array[$j];
$array[$j] = $temp;
}
```
递归快排
```php
function quickSortRecursive($array, $start = null, $end = null) {
if ($start === null || $end === null) {
$start = 0;
$end = count($array) - 1;
}
if ($start < $end) {
$pivotIndex = partition($array, $start, $end);
quickSortRecursive($array, $start, $pivotIndex - 1);
quickSortRecursive($array, $pivotIndex + 1, $end);
}
return $array;
}
function partition($array, $start, $end) {
$pivot = $array[$end];
$i = $start - 1;
for ($j = $start; $j < $end; $j++) {
if ($array[$j] < $pivot) {
$i++;
swap($array, $i, $j);
}
}
swap($array, $i + 1, $end);
return $i + 1;
}
function swap(&$array, $i, $j) {
$temp = $array[$i];
$array[$i] = $array[$j];
$array[$j] = $temp;
}
```
表格比较
| 方法 | 迭代快排 | 递归快排 |
|---|---|---|
| 空间复杂度 | O(logn) | O(n) |
| 时间复杂度 | O(nlogn) | O(nlogn) |
| 递归深度 | 深度较小 | 深度较大 |
迭代快排和递归快排的时间复杂度相同,都是O(n log n),但迭代快排的空间复杂度更低,因为不需要额外的递归调用栈。在实际应用中,根据具体需求和上下文,可以选择使用迭代或递归的快排算法。






