Algorithm-Insertion Sort (implemented by PHP code)

Introduction

Although the code implementation of insertion sort is not as simple and crude as bubble sort and selection sort, its principle should be the easiest to understand, because anyone who has played poker should be able to understand it in seconds. Insertion sort is the simplest and most intuitive sorting algorithm. Its working principle is to construct an ordered sequence. For unsorted data, scan from back to front in the sorted sequence to find the corresponding position and insert.

Insertion sort, like bubble sort, also has an optimization algorithm called split-half insertion.

1. Algorithm steps
The first element of the first sequence to be sorted is regarded as an ordered sequence, and the second element to the last element are regarded as an unsorted sequence.

Scan the unsorted sequence from beginning to end, insert each element scanned into the proper position of the ordered sequence. (If the element to be inserted is equal to an element in the ordered sequence, the element to be inserted is inserted after the equal element.)

2. Animation demo
Insert picture description here

PHP code implementation

    /**
     * 插入排序
     * @param $arr
     * @return mixed
     */
    public function insertSort($arr)
    {
    
    
        $length = count($arr);

        for ($i=1;$i<$length;$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;
    }
    

Reference article address:

https://www.runoob.com/w3cnote/insertion-sort.html

Guess you like

Origin blog.csdn.net/magentodaddy/article/details/108619421