Home >Backend Development >PHP Tutorial >Insertion Sort Sorting Algorithm Learning-Insertion Sort
Learning of sorting algorithms, insertion sorting, and PHP code implementation.
Idea: Sort from small to large. Compare the newly inserted data with the previous one. If the newly inserted data is smaller than the previous one, swap the order.
<?php //排序--插入 $data = array(10,9,8,7,6,5,4,3,2,1); fun($data); function fun($data){ echo implode(',',$data).'<br>'; $count = count($data); for($i=1;$i<$count;$i++){ echo '第'.($i+1).'个数插入:<br>'; for($j=$i;$j>0;$j--){ if($data[$j]<$data[$j-1]){ echo $data[$j].'<==>'.$data[$j-1].'<br>'; $temp = $data[$j-1]; $data[$j-1] = $data[$j]; $data[$j] = $temp; echo implode(',',$data).'<br>'; } } //echo implode(',',$data).'<br>'; echo '------------------------------<br>'; } }
The above introduces insertion sort and sorting algorithm learning-insertion sort, including the content of insertion sort. I hope it will be helpful to friends who are interested in PHP tutorials.