Insertion Sort

Sort an array using the insertion sort algorithm by building a sorted portion one element at a time.

Code

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

Parameters

Array to sort

Server

More PHP Snippets