anekix anekix - 1 year ago 64
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

#include<iostream>
#include<vector>
#include<algorithm>


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};
bubble_sort(v);

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).