基数排序最优与最坏情况时间代价分析及两类场景差异问询
Great question! Let's break down why radix sort paired with stable counting sort has the same Θ(d(n+k)) time cost for both best and worst scenarios.
First, let's recap how this combination works:
- Radix sort processes numbers digit by digit (usually starting from the least significant digit to the most).
- For each digit position, it relies on a stable counting sort to sort elements based solely on that digit.
The lack of difference between best and worst case comes down to two key points:
1. Counting sort's time doesn't depend on input order
Counting sort is a non-comparison-based algorithm with a fixed Θ(n+k) time cost, no matter what the input's initial state is:
- First, it counts how often each digit value (0-9, since k=10 for decimal numbers) appears in the input—this takes Θ(n) time.
- Next, it builds a prefix sum array to figure out the correct position of each digit in the sorted output—this takes Θ(k) time.
- Finally, it iterates backward through the original array (to keep stability) and places each element in its sorted spot—this takes Θ(n) time.
Whether the input is already sorted, completely reversed, or totally random, these steps run in exactly the same amount of time. There's no shortcut if the input is "nice" and no slowdown if it's "messy."
2. Radix sort's total number of rounds is fixed
The number of rounds d is determined by the maximum number of digits in the input numbers. For example:
- If you're sorting 32-bit integers,
dis 10 (since the largest 32-bit integer has 10 decimal digits). - Even if some numbers have fewer digits, we pad them with leading zeros to match the maximum digit count, so every round processes all
nelements.
Since each round takes Θ(n+k) time, and we run exactly d rounds, the total time always adds up to Θ(d(n+k))—there's no variation based on how the input is structured.
Unlike comparison-based sorts like quicksort (where worst-case time jumps to Θ(n²) vs. best-case Θ(n log n)), radix sort's non-comparison approach with an order-agnostic stable sub-sort ensures its time cost never fluctuates with input order.
内容的提问来源于stack exchange,提问作者EllipticalInitial

