vector<int> coefs(n);
creates a vector of
size `n', filled with 0.
You seem to use `k' to keep the size of the vector, that you use when doing the binary_search(), but when you sort() you use the whole vector
So you have a sorted vector {0, 0, 0, 0, 99} and search for 99 only in the first element.
Your sort function is incorrect
1 2
|
int last = a.size() - 1;
for (int i = 1; i < last; ++i)
|
`last' is a valid position, but you never consider it.
> I use bubble sort because (i think) is the most efficient when the vector is "almost sorted"
Nope. Consider by instance v = {1,2,3,4,5,6,7,8,9,0}. It's ``almost sorted'', you simply need to move the 0 to the first position.
However, bubble-sort would move the 0 only one position in each pass
v = {1,2,3,4,5,6,7,8,9,0}
v = {1,2,3,4,5,6,7,8,0,9}
v = {1,2,3,4,5,6,7,0,8,9}
...
So the time would be O(n^2)
Insertion-sort would work a lot better with a O(n)
However, I don't see a reason for you to maintain the whole vector sorted at each step.
You could simply do
1 2
|
read v
sort v | uniq | count
|
Or, as you are implementing a set, simply use
std::set