Ad space (banner)
๐Ÿ˜PHP Lessons
Lesson 35 / 68

Understanding How Bubble Sort Works

In this lesson you will implement bubble sort and understand the basic mechanics of sorting. This is for anyone searching for "PHP sort implementation".

Bubble sort is a simple algorithm that repeatedly compares two neighbouring values and swaps them when they are the wrong way round. The name comes from the way larger bubbles gradually rise to the surface.

The sample code uses nested for loops: the outer one sweeps the whole array repeatedly while the inner one compares and swaps neighbouring elements. PHP lets you swap two values without a temporary variable using list syntax, as in [$arr[$j], $arr[$j + 1]] = [$arr[$j + 1], $arr[$j]];.

A common stumbling block for beginners is narrowing the inner loop's range correctly. Comparing all the way to the end every time wastes work on the part that is already sorted, so the range needs to shrink pass by pass.

You will almost never write it yourself in production code, but it is the standard first step in learning algorithms. It is not efficient in terms of computational complexity, and in practice you would use an optimised implementation such as sort().

๐Ÿ“– Reference code
โœ๏ธ Your code
Type your code, then press "Run"

๐Ÿงช This site can't compile or run PHP directly, so it checks on the spot whether what you typed matches the reference code (scoring happens entirely in your browser โ€” nothing is sent anywhere).

Ad space (banner)
Ad space (in-article)