function Insertsort (array $container)
{
$count = count ($container);
for ($i = 1; $i < $count; $i + +) {
$temp = $container [$i];
$j = $i-1;
Init
while ($container [$j] > $temp) {
$container [$j +1] = $container [$j];
$container [$j] = $temp;
$j--;
Print_r ($container);
if ($j < 0) break;
}
}
return $container;
}
Print_r (Insertsort ([3, 12, 42, 1, 24, 5, 346, 7]));
$container of output when printing out i=3
Array
( [0] => 3 [1] => 12 [2] => 1 [3] => 42 [4] => 24 [5] => 5 [6] => 346 [7] => 7)Array( [0] => 3 [1] => 1 [2] => 12 [3] => 42 [4] => 24 [5] => 5 [6] => 346 [7] => 7)Array( [0] => 1 [1] => 3 [2] => 12 [3] => 42 [4] => 24 [5] => 5 [6] => 346 [7] => 7)Thus see the array[3] 1, step-by-step move to array[0]. When array[2] > array[3] 1 o'clock into the while loop, swap position,
Array
( [0] => 3 [1] => 12 [2] => 1 [3] => 42 [4] => 24 [5] => 5 [6] => 346 [7] => 7)Then J-1=1, continue to judge when Array[1] of the 1 > array[2] into the while loop, swap position,Array( [0] => 3 [1] => 1 [2] => 12 [3] => 42 [4] => 24 [5] => 5 [6] => 346 [7] => 7)Immediately j-1=0, continue to judge when Array[0] 3 > array[1] 1 into the while loop, swap position,Array( [0] => 1 [1] => 3 [2] => 12 [3] => 42 [4] => 24 [5] => 5 [6] => 346 [7] => 7)The j-1=-1,break exits while. I=4 continue to circulate; get the final result:Array( [0] => 1 [1] => 3 [2] => 12 [3] => 42 [4] => 24 [5] => 5 [6] => 346 [7] => 7)
Insert Sort PHP Version