Pay attention now.
First, stop using the word “frequency”. It is clouding your understanding.
frequency = number of occurrences / total number of samples
Counting sort does not care about frequency. It works on individual number of occurrences directly.
Second, do yourself a favor and click the link I gave you, and take the time to at least watch the animation.
http://www.cplusplus.com/faq/sequences/sequencing/sort-algorithms/counting-sort/
Understanding how the sort works, from start to finish, makes all the difference. Trying to understand code you obtained from somewhere is almost impossible without significant experience — experience you do not have as a beginner.
To recap: Given your input set:
42 42 34 26 42 35 34 47 47
We can put it in a
histogram, which lists each pair as (element, number of times element appears)
0 0
1 0
2 0
...
26 1 ← nonzero
...
34 2 ← nonzero
35 1 ← nonzero
...
42 3 ← nonzero
...
47 2 ← nonzero
...
49 0
50 0
One of the important characteristics of the histogram is that the
keys are
sorted. This happens naturally when you use an array as the histogram, where the indices into the array are the values being sorted, and the elements of the array are the number of times the key appears in the input.
Notice also that the number of times that, say, 15 appeared in the input was
zero. Hence, it will appear zero times in the sorted list.
Since the keys are sorted, we already have a sorted list. The only thing left to do is repeat each element the number of times it appeared in the input.
26 34 34 35 42 42 42 47 47
You should see that there is a
direct correlation between the histogram and the sorted array. The link I gave you takes special care to cover this property — it is the basic premise behind a counting sort, the reason that a counting sort works.
You
must understand this in order to understand a counting sort.
So far, you have used the equivalence == identity property of integers to short-circuit your counting sort. If that is sufficient for your grade, then good enough. But you ought to be aware that it is only half of a proper counting sort. (Read the link!)
Good luck.