Skip to content

Commit

Permalink
Update 8-2.md
Browse files Browse the repository at this point in the history
  • Loading branch information
Peng-Yu Chen committed Oct 17, 2019
1 parent 67524d4 commit 5c94266
Showing 1 changed file with 22 additions and 11 deletions.
33 changes: 22 additions & 11 deletions docs/Chap08/Problems/8-2.md
Original file line number Diff line number Diff line change
Expand Up @@ -22,20 +22,31 @@

**d.** (a) Yes. (b) No. (c) No.

**e.** Using $O(k)$ outside the input-arr.
**e.**

Thanks [@Gutdub](https://github.com/Gutdub) for providing the solution in this [issue](https://github.com/walkccc/CLRS/issues/150).

```cpp
COUNTING-SORT(A, k)
MODIFIED-COUNTING-SORT(A, k)
let C[0..k] be a new array
for i = 0 to k
for i = 1 to k
C[i] = 0
for i = 1 to A.length
C[A[i]] = C[A[i]] + 1 // C[i] now contains the number of elements equal to i
p = 0
for i = 0 to k
for j = 1 to C[i]
p = p + 1
A[p] = i
for j = 1 to A.length
C[A[j]] = C[A[j]] + 1
for i = 2 to k
C[i] = C[i] + C[i - 1]
insert sentinel element NIL at the start of A
B = C[0..k - 1]
insert number 1 at the start of B
// B now contains the "endpoints" for C
for i = 2 to A.length
while C[A[i]] != B[A[i]]
key = A[i]
exchange A[C[A[i]]] with A[i]
while A[C[key]] == key // make sure that elements with the same keys will not be swapped
C[key] = C[key] - 1
remove the sentinel element
return A
```

Not stable, in place, in $O(n + k)$.
In place (storage space is $\Theta(k)$) but not stable.

0 comments on commit 5c94266

Please sign in to comment.