PHP implementation of insertion sort

Foreword

Insertion sort of code to achieve Although there is no bubble sort and selection sort so simple and crude, but it's the principle should be the easiest to understand, because as long as people played poker seconds should be able to understand. Insertion sort is one of the most straightforward sorting algorithm, it works by constructing an ordered sequence, for unsorted data, scan in sorted sequence from back to front, and find the corresponding insertion positions.

Insertion sort and bubble sort, there are also an optimization algorithm, called the demolition of a half insertion.

Algorithm steps

1, the first element to be considered as a first ordered sequence of an ordered sequence, the second element is the last element as unsorted sequence.

2, the sequence from start to finish is not sorted sequentially scanned, the scanning element is inserted into an appropriate position of each ordered sequence. (If the elements to be inserted in an ordered sequence of elements are equal, the elements to be inserted is inserted into the back of the equal element.)

Moving map presentation

PHP code implementation

function InsertSort($arr){
    $num = count($arr);
    // 遍历数组
    for ($i = 1;$i < $num; $i++) {
        // 获得当前值
        $iTemp = $arr[$i];
        // 获得当前值的前一个位置
        $iPos = $i - 1;
        // 如果当前值小于前一个值切未到数组开始位置
        while (($iPos >= 0) && ($iTemp < $arr[$iPos])) {
            // 把前一个的值往后放一位
            $arr[$iPos + 1] = $arr[$iPos];
            // 位置递减
            $iPos--;
        }
        $arr[$iPos+1] = $iTemp;
    }
    return $arr;
}

or

function InsertSort($arr) {
    $length = count($arr);
    for ($i = 0; $i < $length - 1; $i++) {
        for ($j = $i + 1; $j > 0; $j--) {
            if ($arr[$j] < $arr[$j - 1]) {
                $temp = $arr[$j - 1];
                $arr[$j - 1] = $arr[$j];
                $arr[$j] = $temp;
            } else {
                break;
            }
        }
    }
    return $arr;
}

 

Published 109 original articles · won praise 101 · views 360 000 +

Guess you like

Origin blog.csdn.net/Alen_xiaoxin/article/details/105202512