插入排序 php版本
Posted xcvv
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了插入排序 php版本相关的知识,希望对你有一定的参考价值。
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]));
打印出i=3时输出的$container
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
)
从而看出array[3]的1,一步一步移动到array[0]。
当array[2]的42 > array[3]的1 时 进入while循环,互换位置,
Array
(
[0] => 3
[1] => 12
[2] => 1
[3] => 42
[4] => 24
[5] => 5
[6] => 346
[7] => 7
)
随即j-1=1,继续判断
当array[1]的12 > array[2]的1 进入while循环,互换位置,
Array
(
[0] => 3
[1] => 1
[2] => 12
[3] => 42
[4] => 24
[5] => 5
[6] => 346
[7] => 7
)
随即j-1=0,继续判断
当array[0]的3 > array[1]的1 进入while循环,互换位置,
Array
(
[0] => 1
[1] => 3
[2] => 12
[3] => 42
[4] => 24
[5] => 5
[6] => 346
[7] => 7
)
随即j-1=-1,break退出while。
i=4继续循环;
得到最终结果:
Array
(
[0] => 1
[1] => 3
[2] => 12
[3] => 42
[4] => 24
[5] => 5
[6] => 346
[7] => 7
)
以上是关于插入排序 php版本的主要内容,如果未能解决你的问题,请参考以下文章