A: i = 1 while i < n if a[i] < a[i - 1] swap(a[i], a[i - 1]) |
B: max = 0 i = 1 while i < n if a[max] < a[i] max = i swap(a[n - 1], a[max]) |
Both algorithms do O(n) iterations; algorithm A does on swap per iteration and algorithm B does on swap after all iterations are done. It seems that a worst-case analaysis using the size of the array as input and the number of swaps as output is what is wanted. Let's see:
In terms of swaps, algorithm A reduces to
For worst case analysis assume the if-guard is always true and the swap is always taken. Relative to swaps, the while-statement body reduces towhile i < n swap(a[i], a[i - 1])
The while guard contributes no swaps and a worst-case bound of n for the number of iterations, leading towhile i < n O(1)
swaps. Because almost no statements contribute swaps, algorithm B collapses toO(n)*O(1) = O(n*1) = O(n)
which immediately reduces O(1) swaps, an asymptotic improvement over algorithm A.swap(a[n - 1], a[max])
Explain what this extra step does for the counting sort.for i = n - 1 to 1 for j = i - 1 to 0 counts[i] += counts[j]
The counts array is used to make sure the counting sort is stable; that is, to make sure that already sorted elements in the array remain sorted in the same order after the sort.
Stability is important when sorting records having identical primary keys; the order is
The two sorted segments that get merged into a single, larger sorted segment occupy the section of the array into which they will be merged. If the two segments are merged in place, it's possible data could be overwritten during the merge and lost, wrecking the sort.
A degenerate interval set S can be recognized by a value x that appears in each interval (a, b): a ≤ x ≤ b. Because any two intervals S have x in common, they can't appear in the same partition; that is, each partition contains a single interval from S.
This page last modified on 17 February 2006.