You don't implement the obvious optimization to Bubble sort. If you run through the inner loop and no swapping is done then the array is now sorted.
This reduces the "Best Case" complexity to
O(n) rather than the
O(n^2) that you have implemented.
Your sort is based on integers. That is not very useful in C++ as arrays can be of nearly anything. So you should think of this as being able to sort a list of anything.
Sure you say I just change the type
<int> to something I want and recompile.
Sure I say. But if you choose a type
T that is large your code becomes very ineffecient becuase you make copies of the object in the middle of the loop.
int tmp = arr[i]; // You made a copy of the object here.
f = arr[i]; // You made a copy of the object here.
b = arr[i-1]; // You made a copy of another object here.
So each time you are doing a swap you are making three copies of the object.
You can do better by using
std::move() to move the object. Or you can use
std::swap_iter() to do a more efficient job of moving large objects.
Your code assumes that you are sorting a C-array. In C++ we handle things differently we abstract away the container by referring to things with iterators. That way we can sort any type of container by simply providing the iterator.
Now different iterators have different properties and you can potentially optimze the algorithm by the type of the iterator you are using.
Most importantly the code does not work.
You only have a single loop. You need a nested loop (I assume some
You perform a sort of copy paste issue!
I assumed it did not work because I did not understand the hack you did to simulate a second loop. It is still broken.
It is written in a way that makes it hard to read.
Code is designed to be read by humans. Write the code in a away that is easy to read.