I have read a counting sort algorithm which is like this:
Counting Sort(A[1,..n]) //C[1,...k] is the temporary memory and k is the range of integers
for i<-- 1 to k
C[i]<-- 0
for j<-- 1 to n
C[A[j]]<--C[A[j]]+1
for i<--2 to k
C[i]<--C[i]+C[i-1]
for j<--n downto 1
B[C[A[j]]]<--A[j]
C[A[j]]<--C[A[j]]-1
I want to know that if I change the last for to this:for j<--1 to n ,the algorithm will be correct too???(is there any way to show that with this “for” the algorithm will be correct??? )
also in this way the algorithm is stable too?
thanks
The algorithm is correct both ways. It is also stable as you have it right now.
If you change the last
forto what you said, it will stop being stable.Basically,
C[i] = how many elements <= i existafter the end of the thirdforloop. SoC[A[j]]gives you the the last position of an element with valueA[j]in sorted order,C[A[j]] - 1the second last position of an element with valueA[j]and so on. This is why you decrement the values inC.Because of this, you have to start iterating your original array in reverse order if you care about stability: so that the last element with value
xin your original array gets put first in the new array. Iterating your original array in reverse will guarantee thatxis put after all other values equal tox, thus making the algorithm stable.