Create a gist now

Instantly share code, notes, and snippets.

What would you like to do?
Bubblesort using typename template
#include <iostream>
#include <fstream>
#include <vector>
using std::vector;
using std::cout;
using std::endl;
template<typename T>
void print(vector<T> l) {
int i,
n = l.size();
for(i = 0; i < n; ++i) {
cout<<l[i]<<" ";
}
cout<<endl;
};
template<typename T>
void bubblesort(vector<T>& v) {
bool finished = 0,
swapped;
int last = v.size();
while(!finished) {
swapped = false;
for(int i = 0; i < last - 1; ++i) {
if(v[i] > v[i+1]) {
T aux = v[i];
v[i] = v[i+1];
v[i+1] = aux;
swapped = true;
}
}
if( swapped ) last--;
else finished = true;
}
};
template<typename T>
vector<T> _bubblesort(vector<T> l) {
vector<T> v = l;
bool finished = 0,
swapped;
int last = l.size();
while(!finished) {
swapped = false;
for(int i = 0; i < last - 1; ++i) {
if(v[i] > v[i+1]) {
T aux = v[i];
v[i] = v[i+1];
v[i+1] = aux;
swapped = true;
}
}
if( swapped ) last--;
else finished = true;
}
return v;
};
int main() {
vector<int> v = {9,8,7,6,5,4,3,2,1,90};
cout<<"Unsorted list -> ";
print(v);
cout<<"Sorted list -> ";
v = _bubblesort(v);
print(v);
return(0);
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment