anekix
anekix

Reputation: 2563

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;
}

Upvotes: 1

Views: 59

Answers (3)

Abdul Rizwan
Abdul Rizwan

Reputation: 4108

You were trying to swap between ith index only. there was a problem.

#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[j] > v[j+1]){
                std::swap(v[j], v[j+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;
}

Upvotes: 0

v78
v78

Reputation: 2933

A compiling and properly working code for sorting the vector in increasing order.

#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[j] > v[j+1] ){
                std::swap(v[j], v[j+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;
}

Upvotes: 0

6502
6502

Reputation: 114481

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

Upvotes: 1

Related Questions