This is my code:
#include <iostream>
#include <vector>
using namespace std;
int BubbleSort(vector<int>, int);
int main(){
vector<int> lista_y2 {1, 2, 0};
cout << BubbleSort(lista_y2, lista_y2.size()) << endl;
cout << lista_y2[0] << lista_y2[1] << lista_y2[2] << endl;
return 0;
}
int BubbleSort(vector<int> lista_y2, int m){
int swaps{0};
for (int fim {m-1}; fim >= 0; fim--){
for (int inicio {0}; inicio < fim; inicio++){
if (lista_y2[inicio] > lista_y2[inicio+1]){
lista_y2[inicio] = lista_y2[inicio+1] + lista_y2[inicio];
lista_y2[inicio+1] = lista_y2[inicio] - lista_y2[inicio+1];
lista_y2[inicio] = lista_y2[inicio] - lista_y2[inicio+1];
swaps++;
}
}
}
return swaps;
}
It does return the swaps as it's supose to. But when I try to print the elements from the lista_y2 it has not changed after the BubbleSort. Can someone help me fix it please?
You need to pass the std::vector
by reference, or const reference if the function will not modify the parameter. Passing by reference allows your function to modify the parameter.
E.g. : int BubbleSort(vector<int>& lista_y2, int m)
You should pass all large data types by reference so that the compiler doesn't make copies.