Quote:

How to optimize this code for speed any further

Assuming the Elo ranking is positive values only:

- At cost of

`count`

a little larger,

`min`

can be just removed from code.

Assuming you know the range of values of Elo:

- you can set

`max`

to a constant and remove the first loop that search

`max`

.

void TcpServer::sortRankCounting(std::vector<boost::shared_ptr<ServerData::character_object>>& r)
{
if (r.size() == 0) return;
~~ int max = r[0]->elo;
int min = r[0]->elo;
for (int i = 0; i < r.size(); i++) { int elo = r[i]->elo;
if (max < elo)max = elo;
if (min > elo)min = elo;
}
int range = max - min + 1;~~
int range = 4000;
std::vector<int> count(range); std::vector<boost::shared_ptr<ServerData::character_object>> output; output.reserve(r.size()); for (int i = 0; i < r.size(); i++) count[r[i]->elo ~~- min~~]++;
for (int i = 1; i < count.size(); i++) count[i] += count[i - 1];
for (int i = r.size() - 1; i >= 0; i--) { output[count[r[i]->elo ~~- min~~] - 1] = r[i];
count[r[i]->elo ~~- min~~]--;
}
for (int i = 0; i < r.size(); i++) { r[i] = output[i];
r[i]->rank = i;
}
}

[update]

I would also try another thing: replace

for (int i = r.size() - 1; i >= 0; i--) { output[count[r[i]->elo - min] - 1] = r[i];
count[r[i]->elo - min]--;
}

with

for (int i = r.size() - 1; i >= 0; i--) { **output[--count[r[i]->elo - min]] = r[i];**
~~count[r[i]->elo - min]--;~~
}

or

for (int i = r.size() - 1; i >= 0; i--) { **count[r[i]->elo - min]--;**
**output[count[r[i]->elo - min]] = r[i];**
~~count[r[i]->elo - min]--;~~
}

Like chess player ranking ?