Lecture02 Sorting Part 2
Lecture02 Sorting Part 2
& ALGORITHMS
Lecture 2: Sorting
part 2: Sorting in Linear time
Lecturer: Dr. Nguyen Hai Minh
[email protected]
CONTENT
qSorting Lower Bound
o Decision trees
qConclusion
132
132 312
312 231
231 321
321
A: 34 01 23 34 23 C:
B:
A: 34 01 23 34 23 C: 0 0 0 0
B:
for i ← 0 to k-1
do C[i] ← 0
A: 34 01 23 34 23 C: 0 0 0 1
B:
for j ← 0 to n-1
do C[A[ j]] ← C[A[ j]] +1 ⊳ C[i] = |{key = i}|
A: 34 01 23 34 23 C: 1 0 0 1
B:
for j ← 0 to n-1
do C[A[ j]] ← C[A[ j]] +1 ⊳ C[i] = |{key = i}|
A: 34 01 23 34 23 C: 1 0 1 1
B:
for j ← 0 to n-1
do C[A[ j]] ← C[A[ j]] +1 ⊳ C[i] = |{key = i}|
A: 34 01 23 34 23 C: 1 0 1 2
B:
for j ← 0 to n-1
do C[A[ j]] ← C[A[ j]] +1 ⊳ C[i] = |{key = i}|
A: 34 01 23 34 23 C: 1 0 2 2
B:
for j ← 0 to n-1
do C[A[ j]] ← C[A[ j]] +1 ⊳ C[i] = |{key = i}|
A: 34 01 23 34 23 C: 1 0 2 2
0 1 2 3
B: C': 1 1 2 2
for i ← 1 to k-1
do C[i] ← C[i] + C[i–1] ⊳ C[i] = |{key i}|
A: 34 01 23 34 23 C: 1 0 2 2
0 1 2 3
B: C': 1 1 3 2
for i ← 1 to k-1
do C[i] ← C[i] + C[i–1] ⊳ C[i] = |{key i}|
A: 34 01 23 34 23 C: 1 0 2 2
0 1 2 3
B: C': 1 1 3 5
for i ← 1 to k-1
do C[i] ← C[i] + C[i–1] ⊳ C[i] = |{key i}|
A: 34 01 23 34 23 C: 1 0 2 2
0 1 2 3
B: 2 C': 1 1 2 5
A: 34 01 23 34 23 C: 1 0 2 2
0 1 2 3
B: 2 3 C': 1 1 2 4
A: 34 01 23 34 23 C: 1 0 2 2
0 1 2 3
B: 2 2 3 C': 1 1 1 4
A: 34 01 23 34 23 C: 1 0 2 2
0 1 2 3
B: 0 2 2 3 C': 0 1 1 4
A: 34 01 23 34 23 C: 1 0 2 2
0 1 2 3
B: 0 2 2 3 3 C': 0 1 1 3
A: 34 01 23 34 23
B: 0 2 2 3 3
q Digit-by-digit sort.
329 720
457 355
657 436
839 457
436 657
720 329
355 839
n d-digits numbers
O(n+k)
if d is constant
O(d(n+k)) O(n)
and k = O(n)
Nguyen Hai Minh 38 9/19/22
Analysis of Radix sort
• Assume counting sort is the auxiliary stable sort.
• Sort n computer words of b bits each.
Each word can be viewed as having b/r base-2r
digits.
8 8 8 8
Example: 32-bit word
qExample:
o car, bar, care, bare à bar, bare, car, care
o 9, 8, 10, 1, 3 à 1, 10, 3, 8, 9