anekix anekix - 1 year ago 81
C++ Question

whats wrong with the following implementation of bubble sort

Here is my implementation of bubble sort why the output doesn't change?Output is same as input vector not the sorted output


void bubble_sort(std::vector<int> &v){
for( int i = 0; i < (v.size() - 1); i++){
for( int j = 0; j < (v.size() - 1 - i) ; j++){
if(v[i] < v[i+1]){
std::swap(v[i], v[i+1]);


int main(){
std::vector<int> v = {1,9,8,7,6,5,3,2};

for(auto &e : v){
std::cout<<e<<" ";

return 0;

Answer Source

In the test you are using i while instead most probably you wanted to use j (as i is constant in that loop).

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download