算法学习之路 | 插入排序[Php]

Posted ·441 Views·391 Words

思路

  1. 给定一个数组,内容都为数字
  2. 外层执行 count-1次循环
    1. 每次循环将当前对应的键值(有序数组下一位)作为将要插入的数
    2. 从有序数组尾部开始循环两两比较,数组值大于要插入的值则插入在该值的左边并继续与再左边的值比较,直到左边的值小于当前要插入的值
  3. 结束循环获得一个升序数组

 

代码

<?php

$array = array(1,3,5,1,2,35,6,123);
$count_array = count($array);

for($i=1;$i<$count_array;$i++){
    $index = $i - 1;
    $current = $array[$i];
    while($index>=0 && $array[$index] > $current){
        $array[$index+1] = $array[$index];
        $array[$index] = $current;
        $index--;
    }
}

var_dump($array);

?>

Comments

Leave a comment to join the discussion