20 October 2010

Bubblesort a Vector in C++

I have learned from looking through my logs on this site, that consistently the most viewed page is the Bubble sort Multidimensional Array in Java. This got me to wondering if people were here for Bubble sorting, Java or multidimensional arrays. The analytics show that it's mostly searches for Java and sorting that have been attracting visitors to that particular page.

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: