bubble sort


See On Github

Data

Contributor

Generic placeholder thumbnail

by jakobhans

in php

Source Code

<?php
    function bubble_sort($array = [])
    {
        // Just ask one time the length of the array
        $n = count($array);

        if(!$n){
            return $array;
        }
        // Iterate over all the elments
        for($i = 0; $i < $n; $i++){
            $flag = false;
            // Order the array
            for($j = 0; $j < $n - $i - 1; $j++){
                if($array[$j] > $array[$j+1]){
                    $flag = true; 
                    // Swap values
                    $temp = $array[$j+1];
                    $array[$j+1] = $array[$j];
                    $array[$j] = $temp;
                }  
            }
            // Already order
            if(!$flag){
                return $array;
            }
        }
    }
<?php
require "bubble_sort.php"; 

class BubbleSortTest extends PHPUnit_Framework_TestCase{
    // Given an unorder array
    private $test = [4,6,1,6,5,9,4,100,-4,50];

    public function testOrderAnArray(){
        $sorted = $this->test; 
        sort($sorted, SORT_NUMERIC);
        $this->assertEquals($sorted, bubble_sort($this->test));
    }

    public function testNoParameters(){
        $this->assertEmpty(bubble_sort([]));
    }
}