Skip to content

Instantly share code, notes, and snippets.

@Nationalcat
Created June 1, 2023 13:06
Show Gist options
  • Save Nationalcat/410df54c2fdc398028f1dbd3dbf291e8 to your computer and use it in GitHub Desktop.
Save Nationalcat/410df54c2fdc398028f1dbd3dbf291e8 to your computer and use it in GitHub Desktop.
使用 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]));

快速排序法

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]));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment