Bubble Sort Algorithm in PHP

Bubble sort algorithm has a runtime complexity of O(n2) and space complexity of O(1). Find below two implementations of Bubble Sort in PHP. If you want to understand how it works, jump to bottom of the page to see a quick video.

function bubbleSort1($arr) : array
{
    $arrLength = count($arr);

    for ($i = $arrLength - 1; $i > 0; $i--) {

        for ($j = 0; $j < $i; $j++) {
    
            if ($arr[$j] > $arr[$j + 1]) {
                $temp = $arr[$j];
                $arr[$j] = $arr[$j + 1];
                $arr[$j + 1] = $temp;
            }
    
        }
		
    }

    return $arr;
}

The second implementation of Bubble Sort is slightly efficient, because it stop the loop as soon as the array has been sorted.

function bubbleSort2($arr) : array
{
    $arrLength = count($arr);

    do {
        $swapped = false;

        for ($index = 0; $index < $arrLength - 1; ++$index){

            if ($arr[$index] > $arr[$index + 1]) {

                $temp = $arr[$index];
                $arr[$index] = $arr[$index + 1];
                $arr[$index + 1] = $temp;

                $swapped = true;
            }

        }

    } while ($swapped);

    return $arr;
}

Source Code of Algorithm Series: https://github.com/EresDev/Algorithms

Understand Bubble Sort:

Leave a Reply

avatar
  Subscribe  
Notify of