I am now using a counting sort method to do the sorting, and for more detailed explanation about this method, please refer to counting_sort The codes are as follows:
#include <iterator>
#include <limits>
template <typename iterator>
void counting_sort(iterator const &begin, iterator const &end)
{
typedef std::iterator_traits<iterator>::value_type T;
T max = std::numeric_limits<T>::max();
T freq[max+1] = {0};
iterator it;
T c;
for (it = begin; it < end; ++it) {
freq[*it] += 1;
}
for (c = 0, it = begin; c < max; ++c)
while (freq[c]-- > 0) {
*it++ = c;
}
}
while (freq[c]-- > 0) {
*it++ = c;
}
}
I have difficult in using the codes to perform sorting. For example,
int main(void)
{
const int NUM=20;
unsigned char a[NUM];
for(int i=0; i<NUM; i++)
a[i] = i;
a[0] = 100;
a[3] = 15;
std::vector<unsigned char> aArray(a,a+NUM);
counting_sort(aArray.begin(),aArray.end());
for(int i=0; i<aArray.size(); i++)
{
int value = aArray[i];
std::cout<<value<<std::endl;
}
return 0;
}
I always have compilation errors for T freq[max+1] = {0}, the error messages are as follows:
error C2057: expected constant expression
error C2466: cannot allocate an array of constant size 0
Any ideas on how to use the codes? Thanks.
T max = std::numeric_limits<T>::max();and add 1 on the next line, looks like an overflow to me.