Insertion Sort Implementation in PHP
This article explains the insertion sort algorithm, describes how it repeatedly inserts each element into its correct position in a growing sorted portion of the array, and provides a complete PHP function that sorts a numeric array while preserving stability.
Insertion sort works by assuming the sub‑array before the current element is already sorted, then inserting the current element into its proper place by shifting larger elements one position to the right; this process repeats until the entire array is sorted, and the algorithm is stable.
The following PHP function implements insertion sort on an array of numbers, iterating from the second element, comparing it with previous elements, shifting larger values, and inserting the element at the correct position before returning the sorted array.
function insertArrMethod($arr) {
$count = count($arr);
for ($i = 1; $i < $count; $i++) {
//以数组第一个数字为基准
$temp = $arr[$i];
//控制循环并进行交换
for ($j = $i - 1; $j >= 0; $j--) {
if ($temp < $arr[$j]) {
$arr[$j + 1] = $arr[$j];
$arr[$j] = $temp;
} else {
break;
}
}
}
return $arr;
}
$array = insertArrMethod([12,56,32,58,1,25,4,63,21,105,99]);
print_r($array);The function call sorts the sample array and prints the resulting ordered list, demonstrating the correct operation of the insertion sort algorithm.
Laravel Tech Community
Specializing in Laravel development, we continuously publish fresh content and grow alongside the elegant, stable Laravel framework.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.