Linear Ordering
Linear Ordering
Curs 2017
Upper and lower bounds on time complexity of a problem.
9 4 6 1:2
1 2 3 < >=
2:3 1:3
< >= < >=
Proof.
Equivalent to prove: Any decision tree that sorts n elements must
have height Ω(n lg n).
Let h the height of a decision tree with n! leaves,
n! ≤ 2h ⇒ h ≥ lg(n!) > lg( ne )n = Ω(n lg n).
Linear sorting: Counting sort
Assume the input A[1 . . . n], is an array of integers betwen 0 and k.
Need: an array B[1 . . . n] as the output
and an array C [1 . . . k + 1] as scratch.
Counting (A, k)
for i = 0 to k do
do C [i] := 0
end for
for i = 1 to n do
do C [A[i]] := C [A[i]] + 1
end for
for i = 1 to k do
do C [i] := C [i] + C [i − 1]
end for
for i = n downto 1 do
do B[C [A[i]]] := A[i]
C [A[i]] := C [A[i]] − 1
end for
Counting (A, k)
for i = 0 to k do
do C [i] := 0 { O(k)}
end for
for i = 1 to n do
do C [A[i]] := C [A[i]] + 1 { O(n)}
end for
for i = 1 to k do
do C [i] := C [i] + C [i − 1] { O(k)}
end for
for i = n downto 1 do
do B[C [A[i]]] := A[i] { O(n)}
C [A[i]] := C [A[i]] − 1 { O(k)}
end for
Time complexity: T (n) = O(n + k) if k = O(n), then
T (n) = O(n).
Linear sorting: Radix sort
Induction on d.
If d = 1 the stable sorting works. Assume it is true for d − 1,
to sort the d-th digit,
if ad < bd then a will be placed before b,
if bd < ad then b will be placed before a,
if bd = ad then as we are using a stable sorting a and b will remain
in the same order, which by hypothesis was already the correct
one.
Complexity
For n integers, each integer with at most d digits, where each digit
is in the range [0, 9]:
I Counting sort is Θ(9dn),
I Radix with the choice of r = log9 n-digits can sort n d-digit
numbers in logd n Θ(9n).
9
Comparing radix and quicksort: