Insertion sort is a simple sorting algorithm that builds the final sorted array (or list) in one go. It is much less efficient on large lists than most advanced algorithms such as quick sort, stack or merge sort.
Graphical example of insertion sort:
PHP insert The sorted code example is as follows:
<?php function insertion_Sort($my_array) { for($i=0;$i<count($my_array);$i++){ $val = $my_array[$i]; $j = $i-1; while($j>=0 && $my_array[$j] > $val){ $my_array[$j+1] = $my_array[$j]; $j--; } $my_array[$j+1] = $val; } return $my_array; } $test_array = array(3, 0, 2, 5, -1, 4, 1); echo "原始数组:\n"; echo implode(', ',$test_array ); echo "\n排序后数组 :\n"; print_r(insertion_Sort($test_array));
Output:
原始数组: 3, 0, 2, 5, -1, 4, 1 排序后数组 : Array ( [0] => -1 [1] => 0 [2] => 1 [3] => 2 [4] => 3 [5] => 4 [6] => 5 )
Related recommendations: "PHP Tutorial"
This article This is an introduction to the insertion sort method in PHP. I hope it will be helpful to friends who need it!
The above is the detailed content of How to implement insertion sort in PHP?. For more information, please follow other related articles on the PHP Chinese website!