I thought perhaps users may find it useful for a straightforward bubble sort in C++. The sort will take a vector of ints (strings would work or any other data type too but adjust the condition to fit your needs) and perform a basic bubble sort on it. This could easily be changed to support arrays and so forth. The algorithm is the same.
Add this function into any of your programs, porting to Java, JavaScript, PHP, et al. should be no problem. The syntax is mostly similar, save for the variable declarations. I can, if requested write this out however. This sort returns a vector but can easily be modified.
vector<int> bubblesort(vector<int> w)
{
int temp;
bool finished = false;
while (!finished)
{
finished = true;
for (int i = 0; i < w.size()-1; i++)
{
if (w[i] > w[i+1]) {
temp = w[i];
w[i] = w[i+1];
w[i+1] = temp;
finished=false;
}
}
}
return w;
}
This is nothing new and not inventing the wheel. Porting this to any other language would take minimal effort. Let me know any thoughts in the comments.

0 comments:
Post a Comment