You can see why we call this a short algorithm. Even though it's
short, I will explain it anyway.

Basically, this algorithm goes through the entire array and compares
every adjacent pair of elements in the array starting from the first
and working towards the last. This cycle is repeated over and over
until the entire array is sorted.

Notice that at the end of each cycle, the last element, and then
the next to last element, and so on is in place. Thus, the cycle
is shortened by one element each time so that we don't have to bother
with the last elements which are already in place.

Let us walk through this algorithm on an example: 3
2 5 4 1. Note that n = 5.

j is no longer strictly less than n
- i, so we are finished with the Third Iteration.

Fourth Iteration ( i = 3 ): We are now considering the array 2 1.

( j = 1 ):2 > 1, so swap()
and the array is now 1 2.

j is no longer strictly less than n
- i, so we are finished with the Fourth Iteration.

Now i is no longer strictly less than n-1, so we are finished sorting.

Now that you have seen the entire sorting process written out,
the algorithm will make more sense to you.

One of the problems with Bubble Sort is that even when the array
is fully sorted, the sort continues. This problem, however, is easily
remedied: just insert a boolean flag that keeps track of
whether or not the sort called swap()
on anything in the last iteration. If it did not, then the sort
has finished early.

Still, improving the efficiency of the Bubble Sort algorithm is
really quite a useless effort. If you want more efficiency, use
another algorithm. The reason for using Bubble Sort is because
it is easy to type, so making Bubble Sort more complex is not really
all that appealing.

If you would like a usable version of the Bubble Sort algorithm,
there is one below that uses templates. The only efficiency improvement
to Bubble Sort is the early exit flag, since that does not add much
length to the code.