SnapShooter Backups Server, Database, Application and Laravel Backups - Get fully protected with SnapShooter

Data Structure and Algorithm - Bubble Sort

In this tutorial, we will learn a simple sorting algorithm - Bubble Sort.

Problem to Solve

Given a list of numbers as shown below, please sort them in ascending order.

$numbers = [21,25,100,98,89,77];


  • You are required to use Bubble Sort algorithm when sorting the numbers.
  • You are required to implement the algorithm in PHP language.


Bubble Sort works by comparing two values at a time and does it pair by pair. And it iterates until all elements are in place. After each iteration, at least one element is moved to the end of the list. Below is an illustration of the first iteration.


Pseudocode of Bubble Sort algorithm can be written as follows:

FOR each element of the list
    FOR each element of the list
        IF current element greater then next element
            swap the elements
        END IF

The inner loop is considered one iteration and the outer loop makes sure we iterate enough times to sort the list.

PHP Implementation

To implement Bubble Sort in PHP, all we need is two loops. Note that the termination of both loops is: the length of the list - 1. This is to prevent from accessing un-indexed element.

$numbers = [21, 25, 100, 98, 89, 77];
for ($i = 0; $i < (count($numbers) - 1); $i++) {
    for ($j = 0; $j < (count($numbers) - 1); $j++) {
        if ($numbers[$j] > $numbers[$j + 1]) {
            $tmp = $numbers[$j];
            $numbers[$j] = $numbers[$j + 1];
            $numbers[$j + 1] = $tmp;
// Output:
    [0] => 21
    [1] => 25
    [2] => 77
    [3] => 89
    [4] => 98
    [5] => 100

The End

If you like our post, please follow us on Twitter and help spread the word. We need your support to continue. If you have questions or find our mistakes in above tutorial, do leave a comment below to let us know.