氣泡排序法(Bubble Sort)
使用 PHP foreach 實作氣泡排序法
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]));
Last updated