Home > Article > Backend Development > PHP insertion sort implementation code
I will introduce to you the implementation algorithm and code of PHP insertion sort. Friends in need can refer to it.
Insertion sort is to insert a piece of data into the already sorted ordered data, thereby obtaining a new ordered data with the number plus one. Algorithm description: ⒈ Starting from the first element, the element can be considered to have been sorted ⒉ Take out the next element and scan from back to front in the sorted element sequence ⒊ If the element (sorted) is larger than the new element, move the element to the next position ⒋ Repeat step 3 until you find the position where the sorted element is less than or equal to the new element ⒌ Insert the new element into the next position ⒍ Repeat step 2 The code is as follows: <?php /** * php 插入排序 * site bbs.it-home.org * 2013-4-6 */ $arr =array(123,0,5,-1,4,15); function insertSort(&$arr){ //先默认第一个下标为0的数是排好的数 for($i=1;$i<count($arr);$i++){ //确定插入比较的数 $insertVal=$arr[$i]; //确定与前面比较的数比较 $insertIndex=$i-1; //表示没有找到位置 while($insertIndex>=0 && $insertVal<$arr[$insertIndex]){ //把数后移 $arr[$insertIndex+1]=$arr[$insertIndex]; $insertIndex--; } //插入(给$insertval找到位置了) $arr[$insertIndex+1] = $insertVal; } } insertSort($arr); print_r($arr); ?> |