function bubbleSort($nums) {
if (count($nums) <= 1) {
return $nums;
}
// 為每個值去比對所有值
foreach($nums as $currentKey => $currentNum) {
foreach($nums as $nextKey => $nextNum) {
// 如果 `當前值` 比 `被比較的值` 大,則與該值交換位置,已達到遞增排序。如要遞減,則改成小於即可。
if ($nums[$currentKey] < $nums[$nextKey]) {
[$nums[$currentKey], $nums[$nextKey]] = [$nums[$nextKey], $nums[$currentKey]];
}
}
}
return $nums;
}
// 1, 2, 3, 4, 5, 6, 7, 8, 9, 10
print_r(bubbleSort([3, 2, 1, 5, 4, 6, 7, 8, 9, 10]));
function quickSort($targets) {
// 空陣列與單一值的陣列沒得比較
if (count($targets) <= 1) {
return $targets;
}
// 定義需要同時向左與向右排序的空間
$left = [];
$right = [];
// 定義該向左還是向右的比較值(中間值),取最後一個值比較方便
$pivot = array_pop($targets);
foreach($targets as $target) {
// 若值比中間值小,則向右排,反之向左排。此為遞增排序,若要遞減,則改成大於即可。
if ($target < $pivot) {
$left[] = $target;
} else {
$right[] = $target;
}
}
// 藉由遞迴的方式,左邊的陣列持相向左排列,右邊也是。中間值則固定在中間。
return [...quickSort($left), $pivot, ...quickSort($right)];
}
// 1, 2, 3, 4, 5, 6, 7, 8, 9, 10
print_r(quickSort([3, 2, 1, 5, 4, 6, 7, 8, 9, 10]));