Bubble Sort

Bubble sort's one virtue is simplicity. The list is scanned repeatedly, once less than there are elements. Neighboring items are compared and swapped if out of order. Each time through the list you scan one less item because the lightest bubbles (to stick with the metaphor) have risen to the top.

The outermost for loop sets the limit for how far to allow bubbles to rise. The first time through, this is one, because the first element of the array is indexed by zero. After going through the inner loop once, we will be certain that the smallest number will be in the first position of the array. This is because the inner loop will compare the last element to the next to last element, swap them if they are out of order, and then move up ...

Get Core PHP Programming: Using PHP to Build Dynamic Web Sites now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.