# PHP Program for Insertion Sort

Last Updated : 20 Mar, 2024

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.

## Insertion Sort Algorithm

• To sort an array of size N in ascending order, iterate over the array.
• For each element (referred to as the “key”), compare it to its preceding element.
• If the key element is smaller than its predecessor, continue comparing it to the preceding elements.
• Shift the larger elements one position forward to make room for the key element.
• Repeat the process until the array is fully sorted.

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

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

• The worst-case time complexity of the Insertion sort is O(N^2).
• The average-case time complexity of the Insertion sort is O(N^2).
• The best-case time complexity of the best case is O(N).

Article Tags :