Insertion Sort in PHP

In Insertion Sort ,If it is the first element, it is already sorted.Pick next element and compare with all other elements.And Shift all the elements in the sorted sub-list that is greater than the value to be sorted.Repeat the process untill sorted.

Source code :

<?php
 
    $unsorted_numbers = array(3,7,1,26,43,12,6,21,23,73);
 
    function insertionsort($array)
    {
        
        for ($i = 0; $i < count($array); $i++) {
               $val = $array[$i];
		       $j = $i-1;
		while($j>=0 && $array[$j] > $val){
			$array[$j+1] = $array[$j];
			$j--;
		}
		$array[$j+1] = $val;
        }
 
        return $array;
    }
 
    $sorted_numbers = insertionsort($unsorted_numbers);
 
    print_r($sorted_numbers);

Output :

Array
(
    [0] => 1
    [1] => 3
    [2] => 6
    [3] => 7
    [4] => 12
    [5] => 21
    [6] => 23
    [7] => 26
    [8] => 43
    [9] => 73
)

Output :


                

Comments :