Direct insertion sort is to insert an element to be sorted into an already sorted array in order of size. Assuming an unordered array with N elements, N-1 insertions will be performed to complete the sorting.
For example, an unordered array with 5 elements will be inserted and sorted 4 times, such as: $array(15,7,43,22,18)
First time::$ array(15) Insert element 7 into the array, after sorting: $array(7,15)
The second time: $array(7,15) Insert element 43 into the array, after sorting: $array(7 ,15,43)
The third time: $array(7,15,43) Insert element 22 into the array, after sorting: $array(7,15,22,43)
The fourth time: $array(7,15,22,41) Insert element 18 into the array, after sorting: $array(7,.15,18,22,43), complete the sorting.
The code is implemented as follows:
<pre name="code" class="php"><span style="font-size:18px;"><?php function insert_sort($array){ $count=count($array); for($i=1;$i<$count;$i++){ if($array[$i-1]>$array[$i]){ $temp=$array[$i]; $j=$i; while($j>0 && $array[$j-1]>$temp){ $array[$j]=$array[$j-1]; $j--; } $array[$j]=$temp; } } return $array; } $arr=array(4,1,17,9,88,37,43); $res=insert_sort($arr); foreach($res as $key => $values){ echo "key:".($key+1)." value:".$values."<br/>"; } ?>
1 |
|
The above introduces the PHP data structure (4) direct insertion sorting, including aspects of the content. I hope it will be helpful to friends who are interested in PHP tutorials.