You’re accessing outside the vector. When you get to the last iteration of the for
loop in bubbleSort()
, numbers[i]
is the last element of the vector, and numbers[i+1]
is outside. This results in undefined behavior, and in your case it happens to access the -1
that you initially put in the vector and then popped out.
Change the loop to use i < numbers.size()-1
as the repeat test.
You can also fix your input loop so you don’t put -1
in the vector in the first place.
while (cin >> n && n != -1) {
numbers.push_back(n);
}
solved C++ How can I delete -1 from my vector?