login

PHP Insertion Sort

In insertion sort, for each iteration, removes an element from the list and insert it into the correct position in the already-sorted list, until no input elements remain. 

<?php

function insertion_sort($arr) {
    for($j=1; $j < count($arr); $j++) {
        $tmp = $arr[$j];
        $i = $j;
        while(($i >= 0) && ($arr[$i-1] > $tmp)) {
            $arr[$i] = $arr[$i-1];
            $i--;
        }
        $arr[$i] = $tmp;
    }

}


/* test insertion sort */

$arr = array(1,3,2,8,5,7,4,0);

print("Before sorting");
print_r($arr);

insertion_sort($arr);
print("After sorting by using insertion sort");
print_r($arr);

?>