I’m trying to write a Counting sort function but for some reason it’s getting stuck inside my first for loop. Can someone tell me what is wrong with my logic? I’m new to C++ so please explain any answers so that I may learn. Thanks in advance!
EDIT: I only get the problem(window pop-up saying “CountSort.exe has stopped working”) only when I input a maxInt less than 130,000. If I input any number higher than that it works great. The list of numbers I want to sort is from an external .txt file that I read. The numbers are: 1 4 6 2 34 65 2 3 64 2 12 97 56 45 3 43 23 99 2
struct CalcMaxInt
{
int maxInt;
CalcMaxInt () : maxInt(0) {}
void operator () (int i) { if (i > maxInt) maxInt = i; }
};
void countSort(vector<int> &numbers)
{
CalcMaxInt cmi = std::for_each(numbers.begin(), numbers.end(), CalcMaxInt());
int maxInt = cmi.maxInt + 1;
vector <int> temp1(maxInt);
vector <int> temp2(maxInt);
int min = 0;
for (int i = 0; i < numbers.size(); i++)
{
temp2[numbers[i]] = temp2[numbers[i]] + 1;
}
for (int i = 1; i <= maxInt; i++)
{
temp2[i] = temp2[i] + temp2[i - 1];
}
for (int i = numbers.size() - 1; i >= 0; i--)
{
temp1[temp2[numbers[i]] - 1] = numbers[i];
temp2[numbers[i]] = temp2[numbers[i]] -1;
}
for (int i =0;i<numbers.size();i++)
{
numbers[i]=temp1[i];
}
return;
}
I haven’t looked for algorithmic errors, but the temp vectors should be sized up, and initialized to
0(this is just for paranoia, the default initializer forintshould be0).After fixing that, the program seems to run on my system, correctly sorting a reverse sorted array. But, you should test with a more complete set of test cases.
Because of the way counting sort works, the
maxIntparameter needs to be a value at least one larger than the largest value held by the input array.You could modify the function to make a pass over the vector to locate the largest.
Then, you wouldn’t have to pass it in.
You might want to add some code to print out what you read in for your input, so that you are sure it is what you think it ought to be.