Search code examples
c++c++11vectorbubble-sort

c++ vector bubble sort


I use g++ -std=c++11 Sort.cpp to compile my file.

My problem is the bubble sort don't sort.

Maybe I'm passing the vector by value but I don't know is closely my firt time trying work with c++ and I chose use vector library.

My code is:

#include <iostream>
#include <vector>

using namespace std;

void bubbleSort(vector<int> a);

void printVector(vector<int> a);

int main(int argc, char const *argv[])
{
    vector<int> a{3,2,6,1};
    printVector(a);

    bubbleSort(a);
    printVector(a);
}

void bubbleSort(vector<int> a)
{
    bool swapp = true;
    while(swapp)
    {
        swapp = false;
        for (int i = 0; i < a.size()-1; i++)
        {
            if (a[i]>a[i+1] )
            {
                a[i] += a[i+1];
                a[i+1] = a[i] - a[i+1];
                a[i] -=a[i+1];
                swapp = true;
            }
        }
    }
}

void printVector(vector<int> a)
{
    for (int i=0;  i <a.size();  i++)
    {
        cout<<a[i]<<" ";
    }
    cout<<endl;
}

In the main I declare a vector type of int's and make the list {3,2,6,1}

After that e call the function printVector wich pretends print all numbers of vector on console and call bubbleSort function and finally print again.


Solution

  • You need to pass by reference; by making a copy, you sort a temporary copy, and then that's it; it disappears and the original is still unsorted, because, once again, you sorted only a temporary copy of the entire vector.

    So change vector<int> a to vector<int>& a.

    Here's the code, fixed:

    http://coliru.stacked-crooked.com/a/2f118555f585ccd5

    #include <iostream>
    #include <vector>
    
    using namespace std;
    
    void bubbleSort(vector<int>& a);
    
    void printVector(vector<int> a);
    
    int main(int argc, char const *argv[])
    {
     vector<int> a {3,2,6,1};
    
     printVector(a);
    
     bubbleSort(a);
    
     printVector(a);
    
    
    
    }
    
    void bubbleSort(vector<int>& a)
    {
          bool swapp = true;
          while(swapp){
            swapp = false;
            for (size_t i = 0; i < a.size()-1; i++) {
                if (a[i]>a[i+1] ){
                    a[i] += a[i+1];
                    a[i+1] = a[i] - a[i+1];
                    a[i] -=a[i+1];
                    swapp = true;
                }
            }
        }
    }
    
    void printVector(vector<int> a){
        for (size_t i=0;  i <a.size();  i++) {
            cout<<a[i]<<" ";
    
        }
      cout<<endl;
    }