The code runs fine and the algorithm is much faster than insertion sort. I built a modified bucket sort around the parameters given in the HW to sort a vector of ints with 50 iterations and 40000 items.
Being new and not familiar with bucket sorts I haven't found any code examples quite like this one. So my question is about my style and possible room for optimization. How can I streamline this algorithm?
void intVectSort2(vector<int> &V, int M)
{
// declare size for U and V
int uSize = ((M * 2) + 1);
int vectSize = V.size();
// allocate memory for U array and initialize to zeros
int *U = new int[uSize];
for (int i = 0; i < uSize; i++)
U[i] = 0;
// step through M values and increment U when V is equal to M
for (int j = 0; j < vectSize; j++)
{
int val = 0;
int count = 0;
int element = 0;
int iterator = M;
val = V[j];
while (val != iterator)
iterator--;
element = iterator + M;
count = U[element];
count++;
U[element] = count;
}
//load confirmed values in order back into V
int index = 0;
int currentSize = 0;
for (int k = 0; k < uSize; k++)
{
int value = 0;
int counter = 0;
value = U[k];
if (value != 0)
{
while (counter < value)
counter++;
currentSize += counter;
for (index; index < currentSize; index++)
V[index] = k - M;
}
}
// free dynamic memory
delete [] U;
}