Open In App

PHP Program for Insertion Sort

Insertion sort is a simple and efficient sorting algorithm that builds the final sorted array one element at a time. Insertion sort provides several advantages such as simple implementation, efficient for small data sets, and more efficient in practice than most other simple quadratic algorithms like selection sort or bubble sort.

Working of Insertion Sort

Insertion Sort Algorithm

Example: The below mention code implements the Insertion Sort Algorithm in PHP.

<?php 

function insertionSort(array &$arr) {
    $n = count($arr);
    for ($i = 1; $i < $n; $i++) {
        $key = $arr[$i];
        $j = $i - 1;

        while ($j >= 0 && $arr[$j] > $key) {
            $arr[$j + 1] = $arr[$j];
            $j--;
        }
        
        $arr[$j + 1] = $key;
    }
}

function printArray(array $arr) {
    foreach ($arr as $value) {
        echo $value . " ";
    }
    
    echo "\n";
}

// Driver Code
$arr = [12, 11, 13, 5, 6];

insertionSort($arr);
printArray($arr);

?>

Output
5 6 11 12 13 

Time Complexity of Insertion Sort

Article Tags :