From 5c94266437788535a57468a5c0d1b77b2e09f65c Mon Sep 17 00:00:00 2001 From: Peng-Yu Chen Date: Thu, 17 Oct 2019 22:18:57 +0800 Subject: [PATCH] Update 8-2.md --- docs/Chap08/Problems/8-2.md | 33 ++++++++++++++++++++++----------- 1 file changed, 22 insertions(+), 11 deletions(-) diff --git a/docs/Chap08/Problems/8-2.md b/docs/Chap08/Problems/8-2.md index 5a304d52fd..12cb29af2d 100755 --- a/docs/Chap08/Problems/8-2.md +++ b/docs/Chap08/Problems/8-2.md @@ -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.